PowerShell for Windows Admins

Aug 23 2010   12:39PM GMT

WMI date issue



Posted by: Richard Siddaway
Operating System, PowerShell v2

 

Working with WMI dates can be awkward sometimes. For instance if we look at the last boot up time of our system

$machine = Get-WmiObject -Class Win32_OperatingSystem

PS> $machine.LastBootUpTime
20100823183135.359600+060

We get a non-intuitive result

The ConvertToDateTime method can rescue us from this problem

PS> $machine.ConvertToDateTime($machine.LastBootUpTime)

23 August 2010 18:31:35

 

And we can even use it with write-host

PS> Write-Host $machine.ConvertToDateTime($machine.LastBootUpTime)
23/08/2010 18:31:35

 

However if we want to make the boot time part of a larger string we get a problem

PS> Write-Host "$machine.ConvertToDateTime($machine.LastBootUpTime)"
\\RSLAPTOP01\root\cimv2:Win32_OperatingSystem=@.ConvertToDateTime(\\RSLAPTOP01\root\cimv2:Win32_OperatingSystem=@.LastBootUpTime)

 

so we can use a sub-expression

PS> Write-Host "Boot up Time $($machine.ConvertToDateTime($machine.LastBootUpTime))"
Boot up Time 08/23/2010 18:31:35

 

but we end up with date that has changed format and is confusing if you are used to DD/MM/YYYY as we use in the UK. We can then use the DateTime property to get back to the format we need

PS> Write-Host ($machine.ConvertToDateTime($machine.LastBootUpTime)).DateTime
23 August 2010 18:31:35

PS> Write-Host "Boot up Time $($machine.ConvertToDateTime($machine.LastBootUpTime).DateTime)"
Boot up Time 23 August 2010 18:31:35

Done.

Comment on this Post

Leave a comment: