I have a script call "a.ps1":
write-host "hello host"
"output object"
I want to call the script and obtain the output object, but I also want the standard output to be suppressed:
$result = .\a.ps1
# Don't want anything printed to the console here
Any hint?
To silence direct console output and discard all output, you can temporarily disable the internal PowerShell command Out-Default . This command is used privately to write directly to the console. Read more about Out-Default if you like.
Starting in Windows PowerShell 5.0, Write-Host is a wrapper for Write-Information This allows you to use Write-Host to emit output to the information stream. This enables the capture or suppression of data written using Write-Host while preserving backwards compatibility.
In a nutshell, Write-Host writes to the console itself. Think of it as a MsgBox in VBScript. Write-Output , on the other hand, writes to the pipeline, so the next command can accept it as its input. You are not required to use Write-Output in order to write objects, as Write-Output is implicitly called for you.
Since a PowerShell user will have the necessary level of control over an informational message the same as an output or verbose message, the use of Write-Host or Write-Information is encouraged and recommended for use as necessary.
There really is no easy way to do this.
A workaround is to override the default behavior of Write-Host by defining a function with the same name:
function global:Write-Host() {}
This is very flexible. And it works for my simplistic example above. However, for some unknown reason, it doesn't work for the real case where I wanted to apply (maybe because the called script is signed and for security reasons it doesn't allow caller to arbitrarily change the behavior).
Another way I tried was to modify the underlying Console's stdout by:
$stringWriter = New-Object System.IO.StringWriter
[System.Console]::SetOut($stringWriter)
[System.Console]::WriteLine("HI") # Outputs to $stringWriter
Write-Host("HI") # STILL OUTPUTS TO HOST :(
But as you can see, it still doesn't work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With