Posted By: Anonymous
I have a PowerShell script for which I would like to redirect the output to a file. The problem is that I cannot change the way this script is called. So I cannot do:
.MyScript.ps1 > output.txt
How do I redirect the output of a PowerShell script during its execution?
Start-Transcript would work for you. First stop it if it’s already running, then start it, and stop it when done.
$ErrorActionPreference="SilentlyContinue" Stop-Transcript | out-null $ErrorActionPreference = "Continue" Start-Transcript -path C:output.txt -append # Do some stuff Stop-Transcript
You can also have this running while working on stuff and have it saving your command line sessions for later reference.
If you want to completely suppress the error when attempting to stop a transcript that is not transcribing, you could do this:
$ErrorActionPreference="SilentlyContinue" Stop-Transcript | out-null $ErrorActionPreference = "Continue" # or "Stop"