Friday, January 27, 2012

Traversing time with PowerShell

My first title for this was “the PowerShell time machine” because the article is about TimeSpan and managing time using TimeSpan.

Most folks are familiar with Get-Date.  Get-Date is all about ‘now’ – it is always now. 

Which is great, if you are running a script and want to know at some point in the script what the time is ‘now’, such as before entering a loop of some type.

Frequently I need to calculate the difference between then and now.  Or the difference between then and then.  This is where the TimeSpan comes into play.

My current project involves trudging through entries in a log file and finding a start time for a series of steps, and then the end time for the series of steps.  The whole point is that I need to know how long the series of steps took so that we can see if we made it any faster.

I don’t know about you but I have a hard time with determining the minutes in between 09:54:53 and 14:13:33.  That isn’t something I can look at and do in my head.

This is not the most elegant script and I know it can be improved.  However, this is where I began taking basic keyboard text entry and turning it into time.

If you run the script it asks you for the start time, entering HH, then MM, then SS.  Then the end time, again. HH, then MM, then SS.  Then it calculates the difference.

do {
    $startTime = New-TimeSpan -Hours (read-host -prompt "Enter Start hour HH") -Minutes (read-host -prompt "Enter Start minutes MM") -Seconds (read-host -prompt "Enter Start seconds SS")

    $endTime = New-TimeSpan -Hours (read-host -prompt "Enter End hour HH") -Minutes (read-host -prompt "Enter End minutes MM") -Seconds (read-host -prompt "Enter End seconds SS")

    $timeToExecute = $endTime - $startTime

    "   The task took: _" + $timeToExecute.TotalMinutes + "_ minutes"
    $quit = Read-Host -Prompt "press Enter to continue or 00 Enter to quit"
    Clear-Variable -Name startTime
    Clear-Variable -Name endTime

} until ($quit -eq "00")

No comments: