windows 如何在 PowerShell 中比较两个日期并在几分钟内获得差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21882831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Compare two dates in PowerShell & get difference in minutes
提问by user206168
I need to compare LastWriteTime of a file and compare it to the current time. if the difference is greater then 45 minutes then I need to get a email alert.
我需要比较文件的 LastWriteTime 并将其与当前时间进行比较。如果差异大于 45 分钟,那么我需要收到电子邮件警报。
Here is what I got so far.
这是我到目前为止所得到的。
$StartDate=(GET-DATE)
$EndDate=[datetime]”01/01/2014 00:00”
NEW-TIMESPAN –Start $StartDate –End $EndDate
In code above I need to replace $EndDate
with Get-Item C:\Users\myusername\Desktop\file.html | select LastWriteTime
在上面的代码中,我需要替换$EndDate
为Get-Item C:\Users\myusername\Desktop\file.html | select LastWriteTime
I need to compare the LastWriteTime of file.html with current time.
我需要将 file.html 的 LastWriteTime 与当前时间进行比较。
Please help me store
Get-Item C:\Users\myusername\Desktop\file.html | select LastWriteTime
into $EndDate
请帮我
Get-Item C:\Users\myusername\Desktop\file.html | select LastWriteTime
存入$EndDate
so I can do the compare.
所以我可以做比较。
回答by Duncan
I think this should work:
我认为这应该有效:
if (((Get-Date) - (Get-ChildItem file.html).LastWriteTime).TotalMinutes -gt 45) {
Write-Host "Old file"
}
Just to get the date into a variable would be:
只是将日期输入变量将是:
$EndDate = (Get-Item C:\Users\myusername\Desktop\file.html).LastWriteTime
or
或者
$EndDate = Get-Item C:\Users\myusername\Desktop\file.html |
select -expandproperty LastWriteTime
The select -expandproperty
syntax is needed on old versions of Powershell (prior to 3.0) when you might be accessing a property on multiple objects. I don't think it is needed even on Powershell 2 if there is only a single object.
select -expandproperty
当您可能访问多个对象上的属性时,旧版本的 Powershell(3.0 之前)需要该语法。如果只有一个对象,我认为即使在 Powershell 2 上也不需要它。