Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress output from non-PowerShell commands?

I am running a command

hg st

and then checking it's $LASTEXITCODE to check for availability of mercurial in the current directory. I do not care about its output and do not want to show it to my users.

How do I suppress ALL output, success or error?

Since mercurial isn't a PowerShell commandlet hg st | Out-Null does not work.

like image 311
George Mauer Avatar asked May 24 '13 22:05

George Mauer


People also ask

How do I redirect output in PowerShell?

There are two PowerShell operators you can use to redirect output: > and >> . The > operator is equivalent to Out-File while >> is equivalent to Out-File -Append . The redirection operators have other uses like redirecting error or verbose output streams.

What does $_ in PowerShell mean?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.


3 Answers

Out-Null works just fine with non-PowerShell commands. However, it doesn't suppress output on STDERR, only on STDOUT. If you want to suppress output on STDERR as well you have to redirect that file descriptor to STDOUT before piping the output into Out-Null:

hg st 2>&1 | Out-Null

2> redirects all output from STDERR (file descriptor #2). &1 merges the redirected output with the output from STDOUT (file descriptor #1). The combined output is then printed to STDOUT from where the pipe can feed it into STDIN of the next command in the pipline (in this case Out-Null). See Get-Help about_Redirection for further information.

like image 171
Ansgar Wiechers Avatar answered Sep 30 '22 18:09

Ansgar Wiechers


A fun thing you can do is to pipe the output to Write-Verbose, then you can still see it if you need it by running your script with the -Verbose switch.

ping -n 2 $APP 2>&1 | Write-Verbose
like image 32
Dexter Bacchus Avatar answered Oct 01 '22 18:10

Dexter Bacchus


Can also do this

hg st *> $null

Powershell suppress console output

like image 42
Zombo Avatar answered Oct 02 '22 18:10

Zombo