Saturday, September 6, 2014

Using .NET to convert a WMI datetime to a powershell datetime

The datetime format for WMI objects (through powershell) is different from the native powershell datetime format, so you need to convert it to PowerShell's native datetime format.

When using 'local' WMI commandlets, this is easy, just call the objects 'ConvertToDatetime' method. But when automating tasks you would collect data using powershell remoting. The powershell object containing the WMI datetime you obtained using remoting, does have all properties available, but not the methods.
You can create a local WMI object and use it's ConvertToDatetime method, but there is an easier way.

I found that solution by looking for something entirely different in this blog: New way to convert WMI time properties
Simply use [System.Management.ManagementDateTimeconverter]::ToDateTime( ) with the WMI time as the parameter.

This .Net method converts a WMI datetime to PowerShell's native DateTime format. So no need the need to create a local WMI object and then us it's conversion method :)

Example code:

$Computer = 'SERVER01'
$wmiResult = Invoke-Command -ComputerName $Computer -ScriptBlock {
 Get-WmiObject -Class Win32_OperatingSystem -Namespace "root\CIMV2"
 }
if ($wmiResult)
{
    $LastBootTime = [System.Management.ManagementDateTimeconverter]::ToDateTime($wmiResult.LastBootUpTime)
    Write-Output "Server $($wmiResult.PScomputerName) with OS version $($wmiResult.Version), last booted on $LastBootTime"
}
else
{
    Write-Warning "Server $Computer could not be contacted through WS-Man, please check if the server is up and powershell is enabled"
}


If you are only interested in the last boot time and not in other properties, you can do the conversion at the remote computer (at the expense of a larger scriptblock) and just return the already converted date.

No comments:

Post a Comment