Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

powershell - 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.

example:

if the command ran yesterday, the value will be 1

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

or

if (file.exists()) {
  Date lastModified = new Date(file.lastModified());
}

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) extract the (tokens?) sub string of just the date from a date/time modified command

2) removing any colons or slashes

3) convert to an integer

4) repeat for today's date

Once I have two integers subtracting and setting a variable should be easy.

Any recommendations?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In PowerShell you can just subtract one date from another and get a timespan. So something as simple as:

$File = Get-Item C:PathToFile.txt
$DaysSinceMod = [datetime]::now - $File.LastWriteTime | Select -Expand Days

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:PathToFile.txt)|% Days

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...