views:

1675

answers:

4

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 to redirect the output of a Powershell script during its execution?

Thanks!

+4  A: 

One possible solution, if your situation allows it:

  1. Rename MyScript.ps1 to TheRealMyScript.ps1
  2. Create a new MyScript.ps1 that looks like:

    .\TheRealMyScript.ps1 > output.txt

zdan
+1  A: 

Maybe Start-Transcript would work for you. First stop it if it's already running, then start it, and stop it when done.

Stop-Transcript | out-null
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.

Bratch
Note that start-transcript does not record Write-Error, Write-Verbose, or Write-Debug...only standard output.
Richard Berg
+5  A: 

You might want to take a look at the cmdlet Tee-Object. You can pipe output to Tee and it will write to the pipeline and also to a file

Andy Schneider
A: 

There is an open Powershell Connections suggestion, "Script Logging needs to be improved", regarding this issue, that I would encourage everyone to vote on.

Nathan Hartley