Friday, April 16, 2010

Display a PowerShell session’s RAM and CPU utilization in the Title Bar

So, I had a few other things I’ve cooked up this week that I was thinking about posting, but this was too much fun this morning.  Here’s a little bit of code you can stick in your powershell profile that will update the title bar with the current PowerShell session’s memory usage (working set, technically) and CPU utilization.

# Setup the objects for titlebar manipulation            
# Append a #1,#2,#(n-1) to the process name if there are n pre-existing processes with the same            
# name, as this is how the Performance Counter system references the instances.            
$psProcess = gps -id $PID            
$psInstances = (gps -Name $psProcess.name).count            
if ($psInstances -gt 1)            
{            
    $psName = "{0}#{1}" -f $psProcess.name,$($psInstances - 1)            
}            
else            
{            
    $psName = $psProcess.name            
}            
# Create the Performance Counter Object to track our sessions CPU usage            
$Global:psPerfCPU = new-object System.Diagnostics.PerformanceCounter( "Process","% Processor Time", $psName )            
# Get the first 'NextValue', which will be zero            
$psPerfCPU.NextValue() | Out-Null            
# Create a timer object and set the interval to 1 second            
$Global:psTimer   = New-Object System.Timers.Timer            
$psTimer.Interval = 1000            
# Update the window's title bar every time the timer object raises the            
# elapsed event            
Register-ObjectEvent -InputObject $psTimer -EventName Elapsed -Action {            
    $psInfo = Get-Process -id $pid            
    [int]$ws = $psInfo.workingset/1MB            
    [int]$cpu = $psPerfCPU.NextValue() / $env:NUMBER_OF_PROCESSORS            
    $Host.ui.rawui.WindowTitle = "$($CurrentUser.Name) $($Host.Name) $($Host.Version) | $((get-location).ProviderPath) | RAM: $ws MB CPU: $cpu%"            
} | Out-Null            
$psTimer.start()

The hardest part was getting the CPU utilization right, but these two posts spell out the details pretty well:
Happy Friday!