Suppress output from non-PowerShell commands?
Asked Answered
T

3

33

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.

Telemark answered 24/5, 2013 at 22:25 Comment(0)
A
65

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.

Agitprop answered 24/5, 2013 at 22:52 Comment(4)
Awesome. That works. Can you explain what the 2>&1 syntax actually means?Telemark
2>&1 means "redirect standard error to the same place as standard output."Categorical
@Categorical I believe that's what I said, only that I addressed both parts of the operator separately, because other streams could be merged with STDOUT (the success output stream, actually) as well.Agitprop
@AnsgarWiechers - sure. I didn't notice that you had amended your answer after George Mauer asked for clarification.Categorical
R
10

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
Robinett answered 25/5, 2018 at 13:35 Comment(0)
I
7

Can also do this

hg st *> $null

Powershell suppress console output

Izaguirre answered 20/6, 2014 at 16:36 Comment(3)
This won't suppress STDERR for example if hg is not installedTelemark
@GeorgeMauer Neither does my suggestion. Errors thrown by the host environment are not redirected.Agitprop
Note that the *> redirection operator is not available prior to PowerShell v3.Agitprop

© 2022 - 2024 — McMap. All rights reserved.