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?
Dates can be subtracted in PowerShell. The result is a [System.TimeSpan].
If you want to do this in a .bat or .cmd script:
Using a Batch file, you may convert a date into a Julian Day Number in a very simple way via a conversion "function", and then use the number in any way you wish:
For example, using these files:
This is the output:
Note: the data of the files shown use the
DD/MM/YYYY
date format, but the code is correct forMM/DD/YYYY
date format. If your format is different, just adjust the%%c%%a%%b
part in the code.In PowerShell you can just subtract one date from another and get a timespan. So something as simple as:
Then
$DaysSinceMod
would be how many days since the file was last modified. Or, using some shorthand, that can be reduced to: