用于检查文件是否超过特定年龄的批处理脚本

时间:2014-02-13 00:40:13

标签: windows batch-file

我正在寻找答案......我已经在Google上拖了几个小时而且我被卡住了!

我正在Windows Server 2008上编写一个批处理脚本,以供NSClient用作Nagios检查的外部脚本。

我已经让脚本做了一些不同的事情,我只需要它来检查一个文件的年龄!这个文件每天都不一样,但我已经补偿了那部分。基本上,我在寻找:

IF%FILE%(插入代码确定超过20分钟) (如果它超过20分钟)ECHO BLAH BLAH BLAH ELSE GOTO:123

希望你们都能帮忙,我会坚持这个!!

由于

1 个答案:

答案 0 :(得分:4)

如果%age%,则会将1变量设置为older than 20 minutes,否则设置为0

像这样启动它:Checkage.bat "c:\folder\filename.txt"

@echo off
:: Wmic removes regional differences
:: XP Pro can have some filename errors due to the short filename bug
:: XP Home does not have WMIC.EXE

set NumMin=20

call :CheckMins "%~f1"
echo %age%
goto :EOF

:CheckMins
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "stamp=%YYYY% %MM% %DD% %HH% %Min%"
call :DateToMinutes %stamp% NowMins
set "file=%~sf1"

:: can use CreationDate instead of lastmodified

WMIC DATAFILE WHERE name="%file:\=\\%" get lastmodified | find "." >file.tmp
for /f %%a in (file.tmp) do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "filestamp=%YYYY% %MM% %DD% %HH% %Min%"
del file.tmp 2>nul
if not defined yyyy goto :EOF

call :DateToMinutes %filestamp% FileMins

set /a MinsOld=%NowMins%-%FileMins%
if %MinsOld% gtr %NumMin% (set age=1) else (set age=0)
goto :EOF

:DateToMinutes
setlocal
set yy=%1&set mm=%2&set dd=%3&set hh=%4&set nn=%5
if 1%yy% LSS 200 if 1%yy% LSS 170 (set yy=20%yy%) else (set yy=19%yy%)
set /a dd=100%dd%%%100,mm=100%mm%%%100
set /a z=14-mm,z/=12,y=yy+4800-z,m=mm+12*z-3,j=153*m+2
set /a j=j/5+dd+y*365+y/4-y/100+y/400-2472633
if 1%hh% LSS 20 set hh=0%hh%
if /i {%nn:~2,1%} EQU {p} if "%hh%" NEQ "12" set hh=1%hh%&set/a hh-=88
if /i {%nn:~2,1%} EQU {a} if "%hh%" EQU "12" set hh=00
if /i {%nn:~2,1%} GEQ {a} set nn=%nn:~0,2%
set /a hh=100%hh%%%100,nn=100%nn%%%100,j=j*1440+hh*60+nn
endlocal&set %6=%j%&goto :EOF