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 ?
You can redirect the error and warning stream to the output stream separately so instead of doing this
you should be doing this
Adapted from Understanding streams
Applied to your example, this would become
or you can redirect all streams to your file