Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: how to capture (or suppress) write-host

Tags:

powershell

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?

like image 255
KFL Avatar asked Jan 23 '13 01:01

KFL


People also ask

How do I suppress output in PowerShell?

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.

What does PowerShell write-host do?

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.

What is the difference between write-host and write-output in PowerShell?

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.

Should I use write-host?

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.


1 Answers

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.

like image 146
KFL Avatar answered Sep 26 '22 00:09

KFL