Leak Tracking with PowerShell

One of my holiday tasks was to learn some PowerShell. While reading/skimming through a book on the subject, I decided to create a quick script which would track memory utilization for a given application. In the past I've used a stand-alone application which would take a snapshot of all the processes and dump out the memory utilization, number of handles, etc. I would then call this application from a batch file periodically to generate a trend of the resource usage. This was an indispensible tool for tracking memory leaks etc., but required some post processing to filter out only the application I cared about. Using PowerShell I was able to whip up a quick script which gave me much the same information without having multiple processing stages.

 

memsnap.ps1

#

# MemSnapGetHeader - returns the header string.

#

function MemSnapGetHeader([string] $procName = "*")

    {

    $time = get-date

    $header = "MemSnap Report`n"

    $header += "`nStart Time: "

    $header += $time.DateTime

    $header += "`nProcess: "

    $header += $procName

 

    $header += "`n`nTime (s), Threads, Handles, Working Set, Total CPU (s)"

    return $header

    }

 

#

# MemSnapGetLine - returns the current comma delimited stats for the

# given application name.

#

function MemSnapGetLine([string] $procName)

    {

    $procInfo = get-process $procName

 

    # if we get back more than one, just grab the first one

    if($procInfo.length -ge 2)

        {

        $procInfo = $procInfo[0]

        }

 

    # build the stats string

    $ret = "" + $procInfo.Threads.Count

    $ret += ", " + $procInfo.Handles

    $ret += ", " + $procInfo.WS

    $ret += ", " + $procInfo.CPU

 

    return $ret

    }

 

#

# MemSnap - this function is the main processing loop which will gather

# the application stats.

#

# hit Ctrl-C to break out of the loop

#

function MemSnap([string] $procName = "*", [int] $delay = 10)

    {

    $time = 0

 

    $header = MemSnapGetHeader $procName

    $header

 

    while($true)

        {

        $line = "" + $time + ", "

        $line += MemSnapGetLine $procName

 

        # echo out the current stats

        $line

 

        sleep $delay

        $time += $delay

  }

    }

 

 

To run it, first we load the script file, and then we call the monitoring function with the application to track:

> . C:\memsnap.ps1

> MemSnap "explorer"

 

You may need to set script execution permissions if you haven't already:

> Set-ExecutionPolicy RemoteSigned

 

 

As this was my very first PowerShell script, comments about inefficiencies, best practices, etc. are more than welcome...