Recording script output
Problem
I need to record the output from my scripts.
Solution
Use Start/Stop-Transcript.
Oops. I forgot to tell you that I sometimes use ISE as well as the PowerShell console. Hmm. The Transcript cmdlets don’t work in ISE. The Scripting Guys showed how to capture the output of a script that was run in ISE in this recent post http://blogs.technet.com/b/heyscriptingguy/archive/2010/09/25/create-a-transcript-of-commands-from-the-windows-powershell-ise.aspx
OK so I know how to capture out in the console and in ISE but the methods don’t match.
We’ll assume that we want to capture the output of each script independently. We’ll also assume a simple script of
Get-Process
Get-Service
| 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031
| if ($psise) { Clear-Host $file = "c:\test\ise-tran1.txt" $header = @" ********************** Windows PowerShell Transcript Start Start time: $(Get-Date) Username : $env:USERDOMAIN\$env:USERNAME Machine : $env:COMPUTERNAME (Microsoft Windows NT $((Get-WmiObject win32_operatingsystem).version)) ********************** "@ Out-File -FilePath $file -InputObject $header } else { Start-Transcript -Path "c:\test\ps-tran1.txt" } Get-Process Get-Service if ($psise) { $out = "Transcript stopped at $(get-date), output file is $($file) " $out Out-File -FilePath $file -InputObject $out -Append $psISE.CurrentPowerShellTab.Output.Text | Out-File -FilePath $file -Append } else {Stop-Transcript} |
Amending the Scripting Guys script we use the $psise variable to test if we are in ISE or not – if not we start-transcript. If we are in ISE we set the header and output to the transcript file
We then run the script
At the end of the script we test if we are in ISE. if not we stop-transcript. If we are we copy the contents of the Output pane to our file.
This code can either be made part of your script templates or could be set as two functions that are loaded in your profiles.