2014-12-04 54 views
2

我使用這個腳本來計算文件的時間早:文件比批處理文件4分鐘

set "filename=myfile.txt" 
rem extract current date and time 
for /f "tokens=1-5 delims=.:, " %%a in ("%date% %time%") do (
    set day=%%a&set mon=%%b&set yr=%%c&set hr=%%d&set min=%%e 
) 
rem extract file date and time 
for /f "tokens=1-5 delims=.:, " %%a in ('"dir %filename%|find "%filename%""') do 
(
    set fday=%%a&set fmon=%%b&set fyr=%%c&set fhr=%%d&set fmin=%%e 
) 
rem calculate age of file (in minutes) 
set /a "age=((hr*60+min)-(fhr*60+fmin)+(24*60))%%(24*60)" 
set /a "max=8" 
if %age% geq %max% echo.file is older than 8 minutes 

但我有一些錯誤,並糾正我不得不使用下列條件:

if %hr% EQU 08 set hr=8 
if %hr% EQU 09 set hr=9 
if %min% EQU 08 set min=8 
if %min% EQU 09 set min=9 
if %fhr% EQU 08 set fhr=8 
if %fhr% EQU 09 set fhr=9 
if %fmin% EQU 08 set fmin=8 
if %fmin% EQU 09 set fmin=9 

有沒有更簡單的方法來解決問題,而不必使用我創建的那些條件?

+0

是的。批處理日期/時間數學是可怕的。使用其他語言可能會更好 - VBScript或JScript。我會稍微回答一個概念證明。 – rojo 2014-12-04 15:04:47

+0

@rojo:或PowerShell,因爲它的日期非常好。 – jftuga 2014-12-04 15:18:44

+0

我必須在WIN2K服務器上批量運行這個腳本。根據微軟的說法, 08和09不是有效的數字,因爲8和9不是有效的八進制數字。 我只是想簡化這些條件。 – 2014-12-04 17:48:20

回答

1

正如我上面評論的那樣,在數學日期,純批次是可怕的。這是一個混合批處理/ JScript腳本,可以非常輕鬆地計算文件的年齡(編輯:或目錄)。無需擔心小時滾動,日期更改,夏令時或任何其他垃圾。這一切都易peasy檸檬擠-Y自午夜1月1日根據毫秒,1970年

@if (@[email protected]) @then 

:: age.bat filename.ext 
:: get age of file in minutes 

@echo off 
setlocal 

if "%~1"=="" echo Usage: age.bat filename.ext && goto :EOF 
if not exist "%~1" echo %1 not found. && goto :EOF 

for /f %%I in ('cscript /nologo /e:JScript "%~f0" "%~1"') do (
    echo %1 is %%I minutes old. 

    rem :: Now use "if %%I gtr 4" here to take whatever actions you wish 
    rem :: on files that are over 4 minutes old. 

) 

goto :EOF 

:: end batch portion/begin JScript 
@end 

var fso = new ActiveXObject("scripting.filesystemobject"), 
    arg = WSH.Arguments(0), 
    file = fso.FileExists(arg) ? fso.GetFile(arg) : fso.GetFolder(arg); 

// Use either DateCreated, DateLastAccessed, or DateLastModified. 
// See http://msdn.microsoft.com/en-us/library/1ft05taf%28v=vs.84%29.aspx 
// for more info. 

var age = new Date() - file.DateLastModified; 
WSH.Echo(Math.floor(age/1000/60)); 

有關批次/混合動力的JScript腳本,see this GitHub page更多信息。上面使用的樣式與該頁面上的Hybrid.bat類似。

+0

我必須在WIN2K服務器上批量運行這個腳本。根據微軟的說法, 08和09不是有效的數字,因爲8和9不是有效的八進制數字。我只是想簡化這些條件。不管怎麼說,還是要謝謝你! – 2014-12-04 17:52:37

+0

呃......你可以打開回聲,看看這個錯誤發生在哪一行?這肯定是一個簡單的修復。 – rojo 2014-12-05 00:41:36