【问题标题】:Powershell formatting a DatePowershell 格式化日期
【发布时间】:2016-04-19 13:58:43
【问题描述】:

我在“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        :

【问题讨论】:

  • [System.Management.ManagementDateTimeConverter]::ToDateTime

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


【解决方案1】:

前段时间我写了一个类似的函数来将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'

这可能会帮助你。

【讨论】:

  • 这个函数对我有用,你知道我如何将它与 select 语句结合起来,转换日期的部分如 [System.Management.ManagementDateTimeConverter]::ToDateTime($Date)
  • 我找到了方法,这里是例子: PS C:\Users\Administrator\Documents> Get-VMSnapshot -VM "Centos Virtual Machine 2" | Select-Object ElementName,@{Label="CreationTime";Expression={[System.Management.ManagementDateTimeConverter]::ToDateTime($($_.CreationTime))}},注释 |格式列表
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 2023-03-29
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多