Saturday, May 30, 2015

Get boot time of ESXi host in local time with PowerCLI

A co-worker came to me yesterday with a request for something that seemed quite easy but came with an unexpected twist.  He needed to get the boot time for a group of ESXi hosts.  Finding the code for this wasn't hard with a quick google search.

For a single host:
PowerCLI C:\script> (get-vmhost esxhost01.example.local).extensiondata.runtime.boottime

Tuesday, March 31, 2015 1:13:07 AM

Using select makes it easier to report on a group of hosts:

PowerCLI C:\script> get-vmhost | select name,@{Name="BootTime";Expression={$_.extensiondata.runtime.boottime}}

Name                                          BootTime              
----                                          --------          
esxhost01.example.local                       5/1/2015 2:57:32 PM 
esxhost02.example.local                       5/29/2015 1:54:30 PM


Piece of cake!  Except this was UTC time, and it makes more sense for us to report our boot time in local time.  Here's the thing - a [datetime] object in Powershell has a method toUniversalTime() but there is no reverse method to convert UTC to local time.

What's the answer? Use New-Timespan to determine your offset from UTC time and the addhours() method of the [datetime] object.  Your offset from UTC can be calculated as:

$offset = (new-timespan -start (get-date).touniversaltime() -end (get-date)).hours

For one host:
(get-vmhost esxhost01.example.local).extensiondata.runtime.boottime.addhours((new-timespan -start (get-date).touniversaltime() -end (get-date)).hours)

For a group of hosts:
get-vmhost | select name,@{Name="BootTime";Expression={$_.extensiondata.runtime.boottime.addhours((new-timespan -start (get-date).touniversaltime() -end (get-date)).hours)}}

Sorry for the line breaks :)

No comments:

Post a Comment