In Windows PowerShell we can use the Start-Transcript cmdlet to record PowerShell sessions to a text-file. This will record both the commands you
ve run as well as the output from the commands.
Windows PowerShell MVP Jeffery Hicks recently wrote a great tip in his Friday Fun series on his blog, which tells you how to convert a PowerShell transcript into a PowerShell script file. That is, youll get a ps1-file which contains the commands extracted from the transcript. Combined with an object event which triggers when PowerShell exits, this can be set up to happen automatically. Jeff actually blogged another Friday Fun tip a couple years ago which describes how to set up such an object event.
Lets have a look at an example on how this would work. First we launch a new PowerShell session and executes a few commands:
When we exit PowerShell we
ll get two files in a specified log directory:
The transcript file (txt-file) contains all commands, errors and output from our session:
The PowerShell script file (ps1-file) contains a script header and the commands from our session:
This means that every PowerShell session automatically generates a PowerShell script file which can be the foundation for a new script.
To set this up you first need to copy the Export-Transcript PowerShell function from Jeffs blog-post and add it to your PowerShell profile (Microsoft.PowerShell_profile.ps1), in addition to the following:
While this is very useful, there is a few gotchas to be aware of:
- This doesn
t work if your exiting PowerShell using the X button. The PowerShell.Exiting event is only triggered when using the exit command.
- This doesnt work in the Windows PowerShell ISE, since that PowerShell host doesn
t support transcripts.
- If youve customized your PowerS
hell prompt, you`ll need to tweak the Export-Transcript function to match the last letter in your prompt.