Powershell格式化日期

时间:2016-04-19 13:58:44

标签: powershell windows-server-2008 hyper-v

我在" windows 2008 R2"上使用了PowerShell HyperV cmdlet。机器和我正在获取快照的CreationTime。但是,我不认识20160418194131.402718-000之类的日期格式。任何人都可以了解如何将此日期格式化为yyyyMMdd hh:mm:ss这样的格式。感谢

实施例

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        :

1 个答案:

答案 0 :(得分:2)

不久前我写了一个类似的函数来将WMI DateTime字符串转换为普通PowerShell DateTime对象:

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'

这可能会帮助你。