2012 Scripting Games Beginner Event 6: Compute Uptime for Local Computer

This script was my 2nd 5 star script of the games and certainly the most used by myself.

This scenario was to calculate the uptime of a computer in days, hours, minutes and seconds. The full details can be found here

The design points for this one are pretty simple too

  • Your solution only needs to run locally.
  • Your script should be easy to read and easy to understand.
  • Your script is only concerned with the uptime for the local server, calculated with the current time. Do not worry about time zones or about comparing up times with different computers.
  • Pay attention to the formatting of the output and the script itself.

Firstly you need to set the variable for the WMI class

$W32OS = Get-WmiObject -Class Win32_OperatingSystem

Next you need to use the CovertToDateTime script method to convert the current time output into something more reasonable.

$CurrentTime=$W32OS.ConvertToDateTime($W32OS.LocalDateTime)

You use the same script method to convert the timedate of the last bootup time.

$Uptime=$W32OS.ConvertToDateTime($W32OS.LocalDateTime) – $W32OS.ConvertToDateTime($W32OS.LastBootUpTime)

Finally with the output of the script, you combine all the variables to give us the information that we are looking for.

"The computer $env:computername has been up for $($Uptime.Days) days $($Uptime.Hours) hours $($Uptime.Minutes) minutes, $($Uptime.Seconds) seconds as of $($CurrentTime)"

Once it is all combined all together the finished script looks like this

$W32OS = Get-WmiObject -Class Win32_OperatingSystem

$CurrentTime=$W32OS.ConvertToDateTime($W32OS.LocalDateTime)

$Uptime=$W32OS.ConvertToDateTime($W32OS.LocalDateTime) – $W32OS.ConvertToDateTime($W32OS.LastBootUpTime)

"The computer $env:computername has been up for $($Uptime.Days) days $($Uptime.Hours) hours $($Uptime.Minutes) minutes, $($Uptime.Seconds) seconds as of $($CurrentTime)"

And that’s it. I know its not anywhere near complete in how I worked out all the cmdlets. I really wish I had blogged about this as I was doing it.

There you have it, my 5 star script for Beginner Event 6 of the 2012 Scripting Games

Advertisements

About Phill McSherry
Phill McSherry has been working in the Australian IT industry for over 20 years and is the technical manager and solutions architect for managed services provider Titan Solutions - www.titansolutions.com.au

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

%d bloggers like this: