If you get an error message, you need to catch the error stream:
$msg = command 2>&1
or
command 2>error.txt
PowerShell writes its messages to different streams, which can be redirected to files to capture the corresponding output.
- Stream 1 (default): normal output ("STDOUT")
- Stream 2: error messages ("STDERR"), including error messages from external programs
- Stream 3: Warning Messages
- Stream 4: detailed messages
- Stream 5: Debugging Messages
- Stream 6: Informational Messages (PowerShell v5 and later only)
To capture a specific stream in a file, you need to redirect the stream number to the file name. for instance
command 2>"C:\path\to\error.log"
will record all error messages created by command in the file C:\path\to\error.log . Use 2>> instead of 2> if you want to add a file, and not overwrite it every time you start.
You can also combine other threads with STDOUT to process / redirect the entire command:
command >>"C:\path\to\all.log" *>&1
See Get-Help about_Redirection or this Scripting Guy article for more information on streams and redirection.
Things worth noting:
- Redirection
*> appeared in PowerShell v3, so it will not work in PowerShell v2 and earlier versions. - A new thread appeared in PowerShell v5 ( Information , thread No. 6), because people continued to abuse
Write-Host because they did not understand what the cmdlet was intended for.
source share