Scripting Games 2012 comments: #12 date conversions

A few times in the games you were asked for date time based information. Now WMI has a lot of classes that return WMI information. It is in an awkward format though

PS> Get-WmiObject -Class Win32_OperatingSystem | fl *time*

CurrentTimeZone : 60
LastBootUpTime  : 20120505101515.296000+060
LocalDateTime   : 20120505192615.170000+060

This translates as:

Year – four digits
Month – two digits
Day - two digits
Hour - two digits
Minute - two digits
Second - two digits
millionth of second but is usually constrained to milliseconds
minutes difference from GMT (UTC)

Its readable but only if you are used to it.

Ideally we want to convert this to a more reasonable looking date such as

05 May 2012 19:35:03

It is possible to take the WMI information, break it up into its components – its is returned as a string – and create a datetime object. Alternatively you can hunt through the .NET classes and find some date conversion methods.

That’s the hard way.

The easy way is to use the built in functionality on the WMI class!

If you put a WMI class through get-member you will discover a couple of Scriptmethods at the end of the data

PS> Get-WmiObject -Class Win32_OperatingSystem | Get-Member -MemberType ScriptMethod

   TypeName: System.Management.ManagementObject#root\cimv2\Win32_OperatingSystem

Name                MemberType   Definition
----                ----------   ----------
ConvertFromDateTime ScriptMethod System.Object ConvertFromDateTime();
ConvertToDateTime   ScriptMethod System.Object ConvertToDateTime();

They are simple to use

If you need the rest of the data on the object

PS> $os = Get-WmiObject -Class Win32_OperatingSystem
PS> $os.ConvertToDateTime($os.LastBootUpTime)

05 May 2012 10:15:15

or if only want the last bootup time

PS> $os = [wmiclass]"\\.\root\cimv2:Win32_OperatingSystem"
PS> $os.ConvertToDateTime($(Get-WmiObject Win32_OperatingSystem | select -ExpandProperty LastBootUpTime))

05 May 2012 10:15:15

There are variations on these themes.

The conversion routines can be used in calculated fields in select and format cmdlets

See PowerShell and WMI chapters 3 and 4 for more details -

Leave a Reply