[英]Find time difference in minutes using a PowerShell script
I am trying to find the time difference between the last updated time and current time for a file.我正在尝试查找文件的上次更新时间和当前时间之间的时差。 How do I extract TotalMinutes data from the output?如何从 output 中提取 TotalMinutes 数据?
$Date = Get-Date
$Files = gci "C:\Users\ABCD\Documents\command.txt"
ForEach ($File in $Files){
$FileDate = $File.LastWriteTime
}
$DURATION=$Date-$FileDate
Echo $DURATION
Output is coming as below
Days : 0
Hours : 2
Minutes : 21
Seconds : 37
Milliseconds : 311
Ticks : 84973115857
TotalDays : 0.0983485137233796
TotalHours : 2.36036432936111
TotalMinutes : 141.621859761667
TotalSeconds : 8497.3115857
TotalMilliseconds : 8497311.5857
You will not need a loop, after getting a single file:获得单个文件后,您将不需要循环:
$Files = gci "C:\Users\ABCD\Documents\command.txt"
ForEach ($File in $Files){
$FileDate = $File.LastWriteTime
}
In this case, $Files
might as well be $File
, making the loop completely redundant:在这种情况下, $Files
也可能是$File
,使循环完全冗余:
$File = gci "C:\Users\ABCD\Documents\command.txt"
$FileDate = $File.LastWriteTime
In the exact same way you extracted LastWriteTime
, you can get TotalMinutes
:以与提取LastWriteTime
完全相同的方式,您可以获得TotalMinutes
:
$Date = Get-Date
$DURATION = $Date - $FileDate
$DURATION.TotalMinutes
Here is a complete answer:这是一个完整的答案:
$Date = Get-Date
$Files = gci "C:\Users\ABCD\Documents\command.txt"
ForEach ($File in $Files){
$FileDate = $File.LastWriteTime
}
$DURATION=$Date-$FileDate
Write-Host "$($DURATION.TotalMinutes)"
$StartDate=(GET-DATE)
#wait a few seconds
$EndDate=(GET-DATE)
$diff = NEW-TIMESPAN -Start $StartDate -End $EndDate
Write-Output "Time difference is: $diff"
$diff
#to see minutes only
$diff.Minutes
#or seconds
$diff.Seconds
您可以使用以下命令来获取 TotalMinutes
$mins = $DURATION.TotalMinutes
Assuming the file exists, here's a one-liner:假设该文件存在,这是一个单行代码:
((Get-Date) - (Get-ChildItem 'C:\Users\ABCD\Documents\command.txt').LastWriteTime).TotalMinutes
You can either let it echo to the screen as is, or you can assign it to a variable if you want to retain it.你可以让它按原样回显到屏幕上,或者如果你想保留它,你可以将它分配给一个变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.