Writing errors and output to a text file and Console
Have you tried:
.\MyScript.ps1 2>&1 | tee -filePath c:\results.txt
2>&1
is what you're looking for
Note: This answer works great in PowerShell 1.0 and 2.0, but will capture ONLY standard output and errors in PowerShell 3.0 and later.
I wasn't satisfied with any answer I was finding, so I mixed a few and came up with this (in PowerShell 3.0+):
$output = try{your_command *>&1}catch{$_}
With this you can capture all errors and output that are generated by trying to use your_command
.
It catches exceptions when you use a non-existent command:
PS C:\Users\jdgregson> $output = try{your_command *>&1}catch{$_}PS C:\Users\jdgregson> echo $outputyour_command : The term 'your_command' is not recognized as the name of acmdlet, function, script file, or operable program. Check the spelling of thename, or if a path was included, verify that the path is correct and try again.At line:1 char:15+ $output = try{your_command 2>&1}catch{$_}+ ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (your_command:String) [], Comman dNotFoundException + FullyQualifiedErrorId : CommandNotFoundExceptionPS C:\Users\jdgregson>
It catches exceptions when you pass invalid arguments to an existing command:
PS C:\Users\jdgregson> $output = try{cat C:\invalid-path.txt *>&1}catch{$_}PS C:\Users\jdgregson> echo $outputcat : Cannot find path 'C:\invalid-path.txt' because it does not exist.At line:1 char:15+ $output = try{cat C:\invalid-path.txt 2>&1}catch{$_}+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (C:\invalid-path.txt:String) [Ge t-Content], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetCo ntentCommand
And it catches the output if there was no problem with your command at all:
PS C:\Users\jdgregson> $output = try{cat C:\valid-path.txt *>&1}catch{$_}PS C:\Users\jdgregson> echo $outputthis file is really here
It works for your example too:
PS C:\Users\jdgregson> $output = try{Test-Error *>&1}catch{$_}PS C:\Users\jdgregson> echo $outputechoWARNING: warningTest-Error : errorAt line:1 char:15+ $output = try{Test-Error *>&1}catch{$_}+ ~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorExcep tion + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio n,Test-Error
By default only the Success stream of data is passed on to the Output file. To direct errors and warnings you will have to add something like this :
your script 3>&1 2>&1 | Out-file log.txt