Monday, January 9, 2012

Powershell - Using Transcript Cmdlets to Ensure All Host Interaction is Captured

I can't even count how many times I have worked on something and realized, after I closed a session, "I should have recorded what I did."  Either some train of thought could not be reproduced or I simply found something clever and couldn't do it again if I tried.  While listening to Ed Wilson on last week's Thursday Powershell session he commented on something which gave me the idea to add something to my $profile to automatically generate logs when the session starts.  After thinking about it a bit I came up with this snippet in my AllUsersAllHosts profile:
#region Configure automatic logging for all hosts

$logpath = "C:\logs\powershell\$(Get-Date -Format "`yyyyMMdd_hhmmss`").log"

if( -not ([System.IO.Directory]::Exists((Split-Path -Path $logpath)))) {
New-Item -Path (Split-Path -Path $logpath) -ItemType Directory | Out-Null
}
Start-Transcript -Path $logpath -Force | Out-null

#endregion Configure automatic logging for all hosts
To easily access this file, if it exists, you can use this command from within Powershell:
notepad $profile.AllHostsAllUsers
This will throw notify you if the file does not exist only after you open the file. When you attempt to save it, you are forced to renavigate to the path during the save command. I will write up a little script to automate this as well with a quick check before opening the command. Another nice addition for the $profile management module I'm working on.

EDIT: After I posted some extra details came to mind which should go in the file name. I added the host name (what is running Powershell) annd the username (the account) to the logfile name.  This way, it's much easier to track whose logs correspond with which hosts.
$logpath = "C:\logs\powershell\$((Get-Host).Name)_$($env:USERNAME)_$(Get-Date -Format "`yyyyMMdd_hhmmss`").log"

0 comments:

Post a Comment