這是一個純粹的批處理文件返回給定年齡的指定目錄中的所有文件,有以下限制:
要使用腳本 - 我們稱之爲max-aged-files.bat
- 提供命令行參數如下:
max-aged-files.bat 15*60 "D:\BatchFiles"
第一個參數是一個文件在幾秒鐘方面最大年齡;理解簡單的算術表達式,如15*60
。第二個參數是要應用於搜索文件的位置和/或文件模式;您可以在此聲明一個目錄路徑,如"D:\BatchFiles"
,或者像"*.bat"
這樣的文件模式,或像這樣的鏈接;它會省略它,使用當前目錄。
下面是代碼:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem /* Please regard that this script cannot handle dates correctly!
rem so if current date and file date are in different months it fails! */
rem // Retrieve and prepare arguments:
set "MAXAGE=%~1" & rem // (maximum age of files in terms of seconds)
if defined MAXAGE (set /A "MAXAGE=%MAXAGE%+0") else (
>&2 echo ERROR: maximum age not specified! & exit /B 1
)
if %MAXAGE% GEQ 86400 (>&2 echo ERROR: maximum age exceeds range! & exit /B 1)
shift /1
set "LOCATION=%~1"
set "ATTR=%~a1"
set "ATTR=%ATTR:~,1%"
if not defined LOCATION (set "LOCATION=.\*.*") else (
if "%ATTR%"=="d" set "LOCATION=%LOCATION%\*.*"
)
rem /* Gather current date/time in standardised format
rem [like: `YYYYMMDDHHMMSS.UUUUUU+ZZZ`]: */
for /F "delims=" %%I in ('wmic OS GET LocalDateTime') do (
for /F "delims=" %%J in ("%%I") do set "CURRTIME=%%J"
)
rem // Extract `YYYYMMSS` portion from current date/time:
set "CURRDATE=%CURRTIME:~,8%"
rem // Extract `HHMMSS` portion from current date/time only:
for /F "delims=." %%T in ("%CURRTIME:~8%") do (
set "CURRTIME=%%T"
)
rem // Loop through all files at given location:
for %%F in ("%LOCATION%") do (
set "ITEM=%%~fF"
setlocal EnableDelayedExpansion
rem // Gather file date/time in standardised format:
for /F "delims=" %%E in ('
2^> nul wmic DataFile WHERE Name^="!ITEM:\=\\!" GET LastModified ^|^|^
2^> nul wmic DataFile WHERE ^(Name^="!ITEM:\=\\!"^) GET LastModified
') do (
for /F "delims=" %%F in ("%%E") do set "FILETIME=%%F"
)
rem // Extract `YYYYMMSS` portion from file date/time:
set "FILEDATE=!FILETIME:~,8!"
rem // Extract `HHMMSS` portion from file date/time:
for /F "delims=." %%T in ("!FILETIME:~8!") do (
set "FILETIME=%%T"
)
rem // Compute date difference between file and current date:
set /A "DATEDIFF=CURRDATE-FILEDATE"
rem // Continue processing only if date difference is zero or one:
if !DATEDIFF! GEQ 0 if !DATEDIFF! LEQ 1 (
rem // Convert date difference to seconds:
set /A "DATEDIFF*=240000"
rem // Compute time difference, regarding also date difference:
set /A "TIMEDIFF=DATEDIFF+1!CURRTIME!-1!FILETIME!"
rem // Pad time difference to consist of 6 digits [like `HHMMSS`]:
set "TIMEDIFF=000000!TIMEDIFF!" & set "TIMEDIFF=!TIMEDIFF:~-6!"
rem // Convert time difference to seconds:
set /A "TIMEDIFF=1!TIMEDIFF:~-2!-100+60*(1!TIMEDIFF:~-4,-2!-100+60*(1!TIMEDIFF:~-6,-4!-100))"
rem // Return item if
if !TIMEDIFF! LEQ %MAXAGE% (
echo(!ITEM!
)
)
endlocal
)
endlocal
exit /B
日期/時間數學有既不是簡單的,也不純一批很好的解決方案(雖然這是可能的)。考慮Powershell,Java或VBA的那部分。 – Stephan