Gabriel Duchateau
Gabriel Duchateau

Reputation: 111

Powershell formatting a Date

I am using the powershell HyperV cmdlet on a "windows 2008 R2" Machine and I am getting the CreationTime of an snapshot. However I do not recognize the Date format like 20160418194131.402718-000. Can anybody shed some light on how to format this date to a format like yyyyMMdd hh:mm:ss. Thanks

Example

PS C:\Users\Administrator\Documents>  Get-VMSnapshot -VM "Centos Virtual Machine 2" | select ElementName,CreationTime,Notes | format-li
st


ElementName  : Centos Virtual Machine 2 - (4/18/2016 - 3:41:09 PM)
CreationTime : 20160418194131.402718-000
Notes        :

ElementName  : Centos Virtual Machine 2 - (4/19/2016 - 8:52:08 AM)
CreationTime : 20160419125218.382146-000
Notes        : test Note

ElementName  : Centos Virtual Machine 2 - (4/19/2016 - 8:47:29 AM)
CreationTime : 20160419124741.107259-000
Notes        :

ElementName  : Centos Virtual Machine 2 - (4/18/2016 - 3:40:15 PM)
CreationTime : 20160418194047.145440-000
Notes        :

Upvotes: 1

Views: 376

Answers (1)

DarkLite1
DarkLite1

Reputation: 14695

A while ago I wrote a similar function to convert a WMI DateTime string to a normal PowerShell DateTime object:

Function ConvertFrom-WMIDateHC {
<#
    .SYNOPSIS
        Convert a WMI DateTime string to a PowerShell DateTime object

    .DESCRIPTION
        Convert a WMI DateTime string to a PowerShell DateTime object

    .PARAMETER Date
        WMI DateTime string

    .EXAMPLE
        ConvertFrom-WMIDateHC -Date '20160415083857.131846+120'
        Converts the WMI DateTime string '20160415083857.131846+120' to a PowerShell DateTime object 'Friday 15 april 2016 08:38:57'
#>

    Param (
        [Parameter(Mandatory,Valuefrompipeline)]
        [String]$Date
    )
    Process {
        Try {
            [System.Management.ManagementDateTimeConverter]::ToDateTime($Date)
        }
        Catch {
            throw "WMI to PowerShell date conversion failed: $_"
        }
    }
}

ConvertFrom-WMIDateHC '20160418194047.145440-000'

This might help you out to.

Upvotes: 2

Related Questions