首页 文章

在Powershell中匹配具有不同格式的日期

提问于
浏览
1

我试图将启动时间与文件修改日期相匹配,在几分钟之内 .

我可以获取数据,但不知道如何进行计算 . 这是我得到的:

PS E:\> $disk=gci -Attributes hidden E:\filename.ext | Select LastWriteTime
PS E:\> $disk

LastWriteTime
-------------
6/23/2014 12:55:48 PM

PS E:\> $boottime=Get-CimInstance -ClassName win32_operatingsystem | select last bootuptime
PS E:\> $boottime
lastbootuptime
--------------
6/23/2014 12:55:39 PM

我用英语寻找的是一种说法“如果lastwritetime在上次启动时间的5分钟内,那么一切都很好 . 如果没有,一切都很糟糕”

我怎么能用PowerShell做到这一点?

2 回答

  • 1

    我会减去日期时间并使用生成的TimeSpan对象 . 另请注意,使用-ExpandProperty需要使用select-object获取裸值 .

    $disk=gci -Attributes hidden E:\filename.ext | Select -ExpandProperty LastWriteTime
    
    $boottime=Get-CimInstance -ClassName win32_operatingsystem | select -ExpandProperty lastbootuptime
    
    if(($disk-$bootTime).TotalMinutes -lt 5){
      "all is good"
    }
    
  • 1

    嗯,这些都是日期和时间,这是肯定的 . 问题是Get-WMI返回了一些相对无用的疯狂CimInstance对象 . 你 can 做的是将它提供给Get-Date,并产生[DateTime]对象,这非常有用!试试这个:

    $boottime=get-date (Get-CimInstance -ClassName win32_operatingsystem | select -expand lastbootuptime)
    

    然后你可以这样做:

    IF($Disk.Lastwritetime -lt $boottime.addminutes(5)){"All is good!"} else {"There is a disturbance in the force!"}
    

相关问题