Suppressing Output
Simple Methods
| Out-Null
> $NULL
Using Streams (BASH like)
Stream | Cmdlet | Id |
---|---|---|
Debug | Write-Debug | 5 |
Error | Write-Error | 2 |
Informatin | Write-Information | 6 |
Verbose | Write-Verbose | 4 |
Warning | Write-Warning | 3 |
Output | Write-Output | 1 |
Host | Write-Host | 6 |
https://powershell.one/code/9.html |
Redirecting Streams
By default, only the Output stream is assigned to variables. All other streams either are emitted directly to the console, or are hidden (controlled by your preference variables).
To include the information from other streams in your variables, use redirection: take the stream id to redirect the stream to the output stream (&1).
This line redirects errors and warnings to the output stream and assigns them to a variable:
# include errors and warnings in variable results:
$all = Get-Process -FileVersionInfo 2>&1 3>&1`
After you run it, $all
contains the results plus all errors and warnings.
Hiding standard output (STDOUT)
Here is a proof of concept illustrating how you can hide messages emitted by Write-Host
:
& {
Write-Warning "A Warning"
"Regular Output"
Write-Host "This will dissappear!"
} 6>$null
By redirecting stream 6 to null, all outputs from Write-Host
and Write-Information
are discarded. You can append 6>$null
to any command or script call.
Destroy it all
*>&1
Silencing All Output
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.
While you really can’t disable the command (it is hard-coded to PowerShell), you can replace it with your own functions, effectively overwriting it. So here is some example code that runs Get-WindowsUpdateLog
without showing all the status messages:
# temporarily overwrite Out-Default
function Out-Default {}
# run your code (guaranteed no output)
Get-WindowsUpdateLog
# test any other direct console write
[Console]::WriteLine("Hello")
# restore Out-Default
Remove-Item -Path function:Out-Default
As long as Out-Default
is replaced by your own empty function, PowerShell emits no output whatsoever. This applies to scripts as well as interactive commands you may invoke. So make sure you remove your function Out-Default
once you are ready to see output again.
This
Out-Default
trick isn’t as edge-casy as you may think. When you browse user groups you’ll discover plenty of threads that deal with this issue.PowerShell users have resorted to all kinds of creative and complex workarounds to discard direct console output, i.e. running code as a job or in another PowerShell instance with a hidden window.
You know now: that’s a bit of overkill. Simply shadow
Out-Default
for as long as you want to silence PowerShell.