Powershell redirect stderr and stdout to two different places
Joining stdout
and stderr
output streams works like PetSerAl commented, though the syntax is not the most intuitive.
The weirdish syntax of 2>&1
means that stderr
(stream 2) is to be added into the stdout
(stream 1). As this is not actually what you are after, try adapting the other example from the MS page to Powershell:
Or, you can redirect the output to one place, and the errors to another.
dir file.xxx > output.msg 2> output.err
Thus,
$ret = myCommand 2> errors.log
should send errors in a log file and non-errors in the $ret
variable.
A comprehensive explanation in about_Redirection MSDN article.
A Minimal, Complete, and Verifiable example (stdout
to pipe):
PS D:\PShell> -1,5,0,2| ForEach-Object { 15/$_ } 2>"$env:temp\err.txt" | Write-Output
-15
3
7.5
PS D:\PShell> Get-Content "$env:temp\err.txt"
Attempted to divide by zero.
At line:1 char:28
+ -1,5,0,2| ForEach-Object { 15/$_ } 2>"$env:temp\err.txt" | Write-Outpu ...
+ ~~~~~
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
PS D:\PShell>
Another example (stdout
to object):
PS D:\PShell> $x = -1,5,0,2| ForEach-Object { 15/$_} 2>"$env:temp\err.txt"
PS D:\PShell> $x
-15
3
7.5