将日志文件的上次修改日期解析为一个变量 [英] Parse a log file's last modified date into a variable
问题描述
我正在尝试将变量设置为自修改日志文件以来的天数.这样,我可以在下次运行命令时将该值用作标志.
I am trying to set a variable to the number of days since a log file was modified. this way I can use that value as a flag for the next time a command runs.
示例:
如果命令昨天运行,则值为1
if the command ran yesterday, the value will be 1
如果命令在5天前运行,则值为5
if the command ran 5 days ago, the value will be 5
我正在寻找解决类似问题的方法,例如:
I'm seeing methods for similar issues such as:
OR %%f IN (%filename%) DO SET filedatetime=%%~tf
或
if (file.exists()) {
Date lastModified = new Date(file.lastModified());
}
我只是不太了解批处理脚本或Powershell.我愿意在任何一个中运行此脚本.我认为我需要学习的是:
I just don't know batch scripting or powershell very well. I'm open to running this script in either. I think what I need to learn is:
1)从修改日期/时间的命令中提取仅日期的(令牌?)子字符串
1) extract the (tokens?) sub string of just the date from a date/time modified command
2)删除任何冒号或斜杠
2) removing any colons or slashes
3)转换为整数
4)重复今天的日期
一旦我有两个整数,就可以轻松地减去和设置一个变量.
Once I have two integers subtracting and setting a variable should be easy.
有什么建议吗?
推荐答案
在PowerShell中,您可以从另一个日期中减去一个日期并获得一个时间跨度.这样的事情很简单:
In PowerShell you can just subtract one date from another and get a timespan. So something as simple as:
$File = Get-Item C:\Path\To\File.txt
$DaysSinceMod = [datetime]::now - $File.LastWriteTime | Select -Expand Days
然后$DaysSinceMod
将是自文件最后一次修改以来的天数.或者,使用一些速记可以简化为:
Then $DaysSinceMod
would be how many days since the file was last modified. Or, using some shorthand, that can be reduced to:
$LastMod=(get-date)-(gi C:\Path\To\File.txt)|% Days
这篇关于将日志文件的上次修改日期解析为一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!