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.

Thursday, July 3, 2014

First Post, why this blog.

I hesitated long before creating this blog, because it is 'yet another blog', waiting to be abandoned. I plan to use it to document some of the things I worked on and want to remember. 

It happens too often, that I investigate something or solve a problem, make notes, but cannot find those notes a few months later to help solving a similar problem. So, when I make my notes in a blog that is searchable, it should be easier to find the notes again. 

This blog has a purpose for me and one is to organize my notes better, and be able to find them again. The same notes could be useful to others and comments could improve on them. It is also a way to give back to the community.

The main theme of this blog would be IT related  and probably contain scripting related to windows systems.