Earlier this week I showed you how to use PowerShell transcripts. I realized it might be nice to have a log file with a timestamp in the name. You may decide, or be required for auditing purposes, to have a transcript of every PowerShell session. You should be able to modify your profile to call Start-Transcript at the beginning of your session. You don’t even have to call Stop-Transcript. When you exit a PowerShell session, that command is written to the transcript file and it is properly closed. If you close the window without typing exit, the last list of the transcript will be the last prompt you were at. In any case, my parsing function ignores the last line of the transcript file.
But back to the point of this entry.
If you want to create a time stamp log, you can use something like this:
Function Get-Timestamp
{
$n=Get-Date
#pad values with leading 0 if necessary
$mo=(($n.Month).ToString()).PadLeft(2,”0″)
$dy=(($n.Day).ToString()).PadLeft(2,”0″)
$yr=($n.Year).ToString()
$hr=(($n.hour).ToString()).PadLeft(2,”0″)
$mn=(($n.Minute).ToString()).PadLeft(2,”0″)
$sec=(($n.Second).ToString()).PadLeft(2,”0″)
$result=$mo+$dy+$yr+$hr+$mn+$sec
return $result
}
$t=Get-TimeStamp
$newfile=”c:\transcript-“+$t+”.txt”
Start-Transcript $newfile
The function splits up the result of Get-Date, converting each part to a string and padding it with a leading 0 if the length is less than 2. I don’t pad the year because it is returned as the full year.
At the end of it all, you’ll end up with a filename like c:\transcript-11272006144918.txt.
You might also consider creating a filename that includes the servername and saving the file to a network share. If you do this on all your servers managed with PowerShell, you’ll have a central audit site for all your PowerShell management sessions.
Thanks for pointing out Get-Date – it was exactly what I needed!
As opposed to spinning up a bunch of variables and mucking with the string padding stuff you can also use the Get-Date cmdlet with the "-format" parameter then provide it a formatting string for the resulting DateTime value.
The formatting specifiers you can use are provided in the "System.Globalization.DateTimeFormatInfo Class" help topic (I learned that from "get-help Get-Date -detailed" and I just searched for it on the web)
So for example:
>$time = get-date -format yyyyMMdd-HHmmss
>$time
20070531-171231