Calculate total and iteration elapsed time in Powershell


When you are executing long-running scripts you probably want to know how long time each part of the script is taking to execute, and the total run time of the script. The demo script below shows how to use the Get-Date and Get-Random CmdLets.

When calculating elapsed time the substraction will result in a TimeSpan database like the one in C#.

$script:startTime = Get-Date

function GetElapsedTime([datetime]$starttime) 
{
    $runtime = $(get-date) - $starttime
    $retStr = [string]::format("{0} sec(s)", $runtime.TotalSeconds)
    $retStr
}

write-host "Script Started at $script:startTime"
for ($i=1; $i -lt 10; $i++) 
{
    $iterTime = Get-Date ;
    get-process | out-null
    $waitsecs = Get-Random -minimum 1 -maximum 5
    sleep $waitsecs
    $elapsed = GetElapsedTime $iterTime ;
    write-host "   Iteration Time: " $elapsed ;
}

write-host "Script Ended at $(get-date)"
$elapsed = GetElapsedTime $script:startTime
write-host "Total Elapsed Time: " $elapsed;

Happy coding…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s