Sunday, April 3, 2016

PowerShell Tip: Start-Transcript and Stop-Transcript

You are trying to write a powershell script but you don’t know all the right comands to execute and what parameters to pass.  So you write a bunch of commands, out of which many don’t work and some work. After lots of experimentation you finally find the right commands with right parameters that would work for your script. You can do Get-history to get a list of all the commands that were executed. But that history only gets persisted as long as you have the powershell window open. Once you close the window that history is gone. I have closed the console window many times and found myself cursing for having done so because I couldn’t remember those commands. Now I have to again fiddle with those commands. Wouldn’t it be nice if there was something that would record everything you did in a text file? Once you are done experimenting you could tell it to stop recording your session and then you can use that text file for later reference. 
Start-Transcript and Stop-Transcript does just that. Before you start experimenting just tell PowerShell you want to record stuff in a text file and Start-Transcript will do that.  After you are done you can use Stop-Transcript to stop recording.  I like this feature. But there is more.
See in the Start-Transcript you have to provide a txt file and I don’t like providing path information with a uniquename everytime I want to do Start-Transcript and I want it to be automatic.  Below function will create a uniquename of the file based upon a timestamp. Now if you wish to provide a meaningful name then you can do that too. The script will append a unique timestamp to that name.  You can put this function into your profile and it will be available to you when the console loads.
function start-recording {
param(
 [string]$sessName
)
try { stop-transcript } catch {}
$uniqFileName = (get-Date).ToString('MMddyyyyhhmmss');
if([System.String]::IsNullOrEmpty($sessName)){
 Start-Transcript -Path "C:\Scripts\Transcripts\$uniqFileName.txt" -NoClobber 
}
else{
Start-Transcript -Path "C:\Scripts\Transcripts\$sessName$uniqFileName.txt" -NoClobber  
}
}

set-alias stop-recording stop-transcript 
I invoke command -  Start-Recording “webpackge” and a unique file name is created in my scripts/transcripts folder by that name.  The function also does stop-transcript if you execute the function start-recording again so it does saves existing session and starts recording another one.