In Powershell, we can combine the standard output stream with any other stream and then redirect (write) the result to the same file.
Examples:
Powershell -File "C:\myscript.ps1" 2>&1> "C:\log.txt"
Powershell -File "C:\myscript.ps1" 3>&2>&1> "C:\log.txt"
Suppose I use Write-Error and Write-Warning statements in myscript.ps1 and I want to write only the errors and the warnings to the same file.
Note: if I am not mistaken, 1 is the output stream, 2 is the error stream and 3 the warning stream.
My first logical try was then to use 3>&2> – if combining 1 and 2 works, why would not 3 and 2 ? See below:
Powershell -File "C:\myscript.ps1" 3>&2> "C:\log.txt"
However, 3>&2> does not work as a valid redirect operator.
I could get around trying:
Powershell -File "C:\myscript.ps1" 3>"C:\warninglog.txt" 2>"C:\errorlog.txt"
but I really want to write to the same file.
If I try to run:
Powershell -File "C:\myscript.ps1" 3>"C:\log.txt" 2>"C:\log.txt"
it seems the error stream (2) never gets written to log.txt because file is locked by the warning stream.
Is there a way to combine two (or more) output streams into a single stream and redirect the result to the same file ?
Best Answer
The verbose, warning, and debug streams are merged into STDOUT when you run PowerShell scripts via
so you can't redirect them separately anymore. Only the error stream is different, since it seems to go to both STDOUT and STDERR, where it can be redirected by
1>
as well as2>
.Demonstration:
If you want to redirect the verbose, warning, or debug stream separately you must use
-Command
instead of-File
and do the redirection within PowerShell:However, while in CMD you can redirect any handle to any other handle (
3>&2
,1>&5
, ...), PowerShell redirection only supports redirection to either a file (3>C:\out.txt
) or the success output stream (3>&1
). Trying to redirect to any other stream will throw an error:as will redirecting different streams to the same file:
If merging warning and success output is an option for you, you could do something like this:
or like this:
or (redirecting all streams) like this:
Otherwise the only option I see is to redirect to different files: