Search code examples
powershelldatetimewmi

Date conversion yyyymmddhhmm+000


I was trying to fetch the details of SCCM MP from WMI by Powershell. Thing is data i can fetch from WMI but date format is different and i am not able to convert. May be lacking some knowledge.

$query = Get-WmiObject -Query "SELECT * FROM SMS_MPInformation " -Namespace root\ccm\LocationServices -ComputerName "test_vm"

$MP = $query.MP
$Sitecode = $query.SiteCode
$MPLastRequestTime = $query.MPLastRequestTime
$MPLastUpdateTime = $query.MPLastUpdateTime

The output I am getting is ok but format of the date is a bit different.

$MPLastRequestTime = 20191008000158.927000+000

Actually it should be like this.

MPLastRequestTime: 08-Oct-2019 00:01

Can anyone advise me how can I convert it in above format. WMIExplorer tool is able to convert it, so I know there must be some way.


Solution

  • Apart from Ivan Mirchev's helpful answer. you can convert a WMI Timestamp like this:

    $wmiTime = '20191008000158.927000+000'
    $date = [DateTime]::new((([wmi]"").ConvertToDateTime($wmiTime)).Ticks, 'Local')
    

    If you need the date to be in UTC, do

    $wmiTime = '20191008000158.927000+000'
    $date = [DateTime]::new((([wmi]"").ConvertToDateTime($wmiTime)).Ticks, 'Local').ToUniversalTime()
    

    The latter will output

    08-Oct-2019 00:01:58

    Explanation:

    Although the WMI timestamp is UTC time, the ConvertToDateTime() function returns the date in Local time, but unfortunately leaves the Kind property set to 'Unspecified'.

    When you perform a ToLocalTime() on it, that method then assumes it's UTC and adds the time zone offset again, resulting in the wrong time.

    Because the .Kind property is read-only on a DateTime object, you need to create a new DateTime using the converted WMI time in order to set its Kind property to 'Local'.