I was going to post a blog entries and realized that the example I wanted to give used some of my utility functions so I’ll share them first. I hope you find them interesting. I put them in a file called LibraryTime.ps1 and dot source that during my login. BTW – everyone should adopt that pattern. Files that contain functions meant to be dot sourced into another script should be called LibraryXXXX.ps1
function Measure-TimeSpan([TimeSpan]$Span, $Units=$Null)
{
switch ($Units)
{
“Weeks” {[Int]($Span.TotalDays / 7)}
“Days” {[Int]$Span.TotalDays}
“Hours” {[Int]$Span.TotalHours}
“Minutes” {[Int]$Span.TotalMinutes}
“Seconds” {[Int]$Span.TotalSeconds}
“MilliSeconds” {[Int64]$Span.TotalMilliSeconds}
“Ticks” {$Span.Ticks}
default {$null}
}
}
function Measure-Since([DateTime]$Time, $Units=$Null)
{
$Since = Measure-TimeSpan $([DateTime]::Now – $Time) $Units
if ($Since -eq $null)
{
throw ‘Usage: Measure-Since -Time <DateTime> -Units [“Weeks”,”Days”,”Hours”,”Minutes”,”Seconds”,”Milliseconds”,”Ticks”]’
}
else
{
$Since
}
}
function Measure-Till([DateTime]$Time, $Units=$Null)
{
$Since = Measure-TimeSpan $($Time – [DateTime]::Now) $Units
if ($Since -eq $null)
{
throw ‘Usage: Measure-Till -Time <DateTime> -Units [“Weeks”,”Days”,”Hours”,”Minutes”,”Seconds”,”Milliseconds”,”Ticks”]’
}
else
{
$Since
}
}
Set-Alias MSince Measure-Since
Set-Alias MTill Measure-Till
Now let’s try them out:
PS> “weeks”,”Days”,”Hours”,”Seconds”,”Milliseconds”,”ticks” |
>> %{ “{0,16} $_” -f (Measure-Since “12/25/2005” $_)}
38 weeks
267 Days
6398 Hours
23034210 Seconds
23034209798 Milliseconds
230342098115960 ticks
PS> “weeks”,”Days”,”Hours”,”Seconds”,”Milliseconds”,”ticks” |
>> %{ “{0,16} $_” -f (Measure-Till “12/25/2006” $_)}
14 weeks
98 Days
2362 Hours
8501789 Seconds
8501788713 Milliseconds
85017886963120 ticks
Enjoy
Jeffrey Snover [MSFT]
Windows PowerShell/Aspen Architect
Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx
PSMDTAG:DOTNET Datetime
0 comments