【问题标题】:Trouble comparing created date with current date无法将创建日期与当前日期进行比较
【发布时间】:2013-05-02 07:28:35
【问题描述】:

希望有人能帮帮我。我无法将当前日期与创建文件的日期进行比较。我从每个日期得到的输出以及我的代码如下所示。

创建日期输出:

21/05/2012 晚上 10:27:25

当前日期输出:

2013 年 8 月 5 日上午 12:00:00

可以比较这些日期吗?

我的代码如下:

$host = Read-Host 'Host: '
$username = Read-Host 'Username: '
$password = Read-Host 'Password: '

Connect-VIServer -Server $host -User $username -Password $password

$snapshotDate = Get-Snapshot -VM CONVCORPSPOINT | Select-Object Created | Format-Table -HideTableHeaders
$currentDate = Get-Date | Select-Object Date | Format-Table -HideTableHeaders

$snapshotDate
$currentDate

if ($snapshotDate -lt $currentDate) {
    Write-Host 'The snapshot date is earlier than the current date'
}
else {
    Write-Host 'The snapshot date is not earlier than the current date'
}

【问题讨论】:

    标签: powershell powershell-2.0 vmware powercli


    【解决方案1】:

    一种常见的解决方案是仅与日期部分(不包括时间部分)进行比较。您可以通过比较 Date 属性(将时间设置为午夜)来做到这一点:

    $date.Date
    

    或者通过显式比较短字符串:

    $date.ToShortDateString()
    

    【讨论】:

      【解决方案2】:

      试试这个:

      $x = Get-Date
      

      您可以获得与日期对象关联的所有方法的列表:

      $x | gm
      

      你可以像这样格式化你的日期:

      $x.ToString("yyyyMMdd hh:mm:ss")
      

      所有格式选项都在here 中描述。 然后,您可以标准化您的日期并轻松进行比较。

      【讨论】:

      • 感谢您的回答。我可以看到这将如何与标准 powershell 语句一起使用,但是我忽略了从 get-snapshot 返回的日期与 VMware 的 PowerCLI 专门相关,并且将日期转换为字符串不起作用(当然对于 get-date )。我会将此标记为答案。
      猜你喜欢
      • 2017-05-15
      • 2019-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多