How to automatically convert Windows PowerShell transcripts into script-files

In Windows PowerShell we can use the Start-Transcript cmdlet to record PowerShell sessions to a text-file. This will record both the commands youve 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 well 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:


#Define variable for the transcript path, which well use to generate the path to the ps1-file
$transcriptlog = ("C:PS-logsPS-Transcript_"+"{0:yyyy-MM-dd_HH-mm-ss}" -f (Get-Date)+".txt")
Start-Transcript -Path $transcriptlog | Out-Null

#Export transcript to ps1-file on exit
Register-EngineEvent PowerShell.Exiting â€“action {
 -Transcript $transcriptlog -Script (($transcriptlog.Replace("Transcript","Script")).Replace("txt","ps1"
| Out-Null


While this is very useful, there is a few gotchas to be aware of:

  • This doesnt 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 doesnt 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.