Saturday, August 18, 2007

Getting System up time (locally)


Here is another way to get your servers up time (total time since last reboot).
This method works locally.

The .NET Environment class exposes the TickCount property. TickCount Gets the number of milliseconds elapsed since the system started. It's a 32-bit signed integer type and by its restrictions it will be "reset" back to zero every 49.7 days (see Environment.TickCount Property on MSDN).

>> [environment]::tickcount;
297580406

To format the result to something more meaningful we'll use the New-TimeSpan cmdlet.
New-TimeSpan doesn't expose a milliseconds parameter so we'll divide the tickcount result by 1000 and feed the New-TimeSpan -seconds parameter.

>> New-TimeSpan -seconds ([environment]::tickcount / 1000);

Days : 3
Hours : 10
Minutes : 42
Seconds : 42
Milliseconds : 0
Ticks : 2977620000000
TotalDays : 3.44631944444444
TotalHours : 82.7116666666667
TotalMinutes : 4962.7
TotalSeconds : 297762
TotalMilliseconds : 297762000

So, to get only the days since last reboot:

>> (New-TimeSpan -seconds ([environment]::tickcount / 1000)).days;
3

Another formatting variation:

>> $sup = New-TimeSpan -seconds ([environment]::tickcount / 1000);
>> [string]::format("D:{0:00},H:{1:00},M:{2:00}",$sup.days,$sup.hours,$sup.minutes);

D:03,H:10,M:53

But wait, There's more. Browsing to the TimeSpan class page at MSDN reveals that TimeSpan class has a TimeSpan.FromMilliseconds Method.

>> [timespan] gm -static fr*;

TypeName: System.TimeSpan
Name MemberType Definition
---- ---------- ----------
FromDays Method static System.TimeSpan FromDays(Double value)
FromHours Method static System.TimeSpan FromHours(Double value)
FromMilliseconds Method static System.TimeSpan FromMilliseconds(Double value)
FromMinutes Method static System.TimeSpan FromMinutes(Double value)
FromSeconds Method static System.TimeSpan FromSeconds(Double value)
FromTicks Method static System.TimeSpan FromTicks(Int64 value)


Now, we can provide milliseconds to TimeSpan in a "static notation form":

>> $sup = [timespan]::FromMilliseconds([environment]::tickcount);
>> [string]::format("{0:00}:{1:00}:{2:00}",$sup.days,$sup.hours,$sup.minutes);

03:11:04

Note: If the returned values are negative, we can use the [math]::abs method to return absolute values.

Shay

No comments: