Date-time objects give you a sense of a script's performance.
By Jeffery Hicks
In PowerShell I'm often wondering how long a particular script or process took to complete. It's a great way to gauge a script's performance in a non-scientific sort of way. Fortunately, you can do this in PowerShell using Date-time objects. PowerShell is smart enough to be able to subtract two date-time objects. All you need is a beginning time and end time.
In your script or at the console, before you run your lengthy command, run this:
$start=Get-Date
Then, run your command. Or if you just want to see what I'm talking about, wait a few minutes pretending something is running, then type:
$end=Get-Date
The runtime will be the difference between the two. I like to create a variable:
$runtime=$end-$start
If you look at $runtime, you should see output like this:
Days : 0
Hours : 0
Minutes : 13
Seconds : 24
Milliseconds : 292
Ticks : 8042925552
TotalDays : 0.00930894161111111
TotalHours : 0.223414598666667
TotalMinutes : 13.40487592
TotalSeconds : 804.2925552
TotalMilliseconds : 804292.5552
To display any part of $runtime all you need to do is use a command like:
$RunTime.TotalSeconds
What I prefer to do in my script or session is to use a single-line expression like this (it's wrapping here, so remember to type this as a single line):
Write-host Process took $Runtime.Days days $Runtime.Hours hours $Runtime.minutes minutes
$Runtime.Seconds seconds $runtime.milliseconds milliseconds
As a faster alternative, you can use this:
$runtime | format-table -auto
Because $runtime is an object, you can do all sorts of things with it, such as checking the number of minutes and, if it exceeds a certain value, display the time in red. I'm sure you'll think of other ways to leverage this information.
Comment: http://mcpmag.com/columns/article.asp?EditorialsID=1830#post
Jeffery Hicks MCSE, MCSA, MCT is a senior network engineer with Visory Group. He's a contributing editor to ScriptingAnswers.com and the coauthor, with Don Jones, of "Advanced VBScript for Microsoft Windows Administrators" (Microsoft Press, http://tinyurl.com/g63nf ) and "PowerShell TFM" (SAPIEN Press, http://tinyurl.com/2v7dye ). Jeff is also the creator of several popular, script-related tools used for network and Exchange administration. He maintains a blog at http://jdhitsolutions.blogspot.com .
