Reputation: 187
I have a script that is being called a certain way, i cannot change it. I want to redirect the error messages from the entire script to a file. How does this work?
I did this, which works, except the errors are complete gone:
$ErrorActionPreference="SilentlyContinue"
Start-Transcript -path C:\output.txt -append
write-host "test"
some nonsence that creates as error
Stop-Transcript
Thanks
Upvotes: 0
Views: 9817
Reputation: 51
Since Powershell 5.1, there are "Redirectable output streams" with bash-like similar syntax, e.g.
Write-Output "good" > success.txt
Write-Error "failed" 2> error.txt
Write-Warning "attention" 3> warning.txt
You can also redirect error to success stream.
./script.ps1 2>&1 > out.log
Alternatively, to redirect all streams when running a script or command, use
.\script.ps1 *> $null # suppress all output
See about_Redirection for more details.
Upvotes: 1
Reputation: 2357
Beware using Start-Transcript. You might get the following error:
Start-Transcript : This host does not support transcription.
At D:\Apps\TranscriptTest\TranscriptTest.ps1:3 char:1
+ Start-Transcript -Path Log.txt -Append
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [Start-Transcript], PSNotSupportedException
+ FullyQualifiedErrorId : NotSupported,Microsoft.PowerShell.Commands.StartTranscriptCommand
Upvotes: 0
Reputation: 2542
Would this work for you?
try{
# your code goes here
}
catch{
$exception = $_.Exception.Message
Out-File -FilePath 'c:\myscript.log' -Append -InputObject $exception
}
Upvotes: 2
Reputation: 415
I needed something like this before, but i could change how the file is being called etc.
If its launched from commandline as mentioned, by arco444, you can use the below to pipe everything to one file:
PowerShell.exe -Command "& {c:\myscript.ps1}" > c:\myscript.log
Upvotes: 0