2012-09-14 14 views
3

Я хочу написать командный файл, который будет проходить через все каталоги, содержащие каталог резервных копий и удалять файлы старше X дней внутри него. На компьютере, на котором я хочу запустить мой скрипт, нет команды «forfile». Нет PowerShell, поэтому CMD или VBScripts - это единственный способ выполнить эту задачу.Windows CMD - set for for loop не работает

В настоящее время у меня проблема с оператором «set» - кажется, что когда я звоню % checkpath% Я не получил ожидаемую папку.

rem we will memorize current directory 
pushd %cd% 
set folder="C:\Documents and Settings\myname\Desktop" 
cd %folder% 
rem loop only folders with five chars within their names (unfortunately on less also 
for /D %%g in (?????) DO (
    set checkpath="%cd%\%%g\backup" 
    if exist %checkpath% (
     for %%a in ('%%g\backup\*.*') do (
     set FileDate=%%~ta 
     set FileDate=%%FileDate:~0,10%% 
     rem here I want to compare file modification data with current date 
     ) 
    ) 
popd 
pause 
+0

Возможный дубликат [Почему эта партия переменная никогда не изменяется даже при установке?] (https://stackoverflow.com/questions/3949978/why-does-this-batch-variable-never-change-even-when-set) –

ответ

8

Вы должны использовать замедленное расширение читать переменную, которую Вы установили внутри for цикла.

Попробуйте вместо

setlocal enabledelayedexpansion 
rem we will memorize current directory 
pushd %cd% 
set folder="C:\Documents and Settings\myname\Desktop" 
cd %folder% 
rem loop only folders with five chars within their names (unfortunately on less also 
for /D %%g in (?????) DO (
    set checkpath="%cd%\%%g\backup" 
    if exist !checkpath! (
     for %%a in ('%%g\backup\*.*') do (
     set FileDate=%%~ta 
     set FileDate=!%FileDate:~0,10%! 
     rem here I want to compare file modification data with current date 
     ) 
    ) 
popd 
pause 

Замена % 's с !-х на переменных, которые вы создали, будет сигнализировать его использовать замедленное расширение вместо этого.

1

Ответ Бали имеет небольшую ошибку. Второй код set filedate неверен, в противном случае его штраф, но может не работать, если вы не включили задержанное расширение. Я исправил его ошибку и показал вам, как обеспечить задержку расширения. Я также сделал некоторые изменения:

::This command will ensure that the delayed expansion, i.e. the "!"s below, 
:: will work. Unfortunately, it also means you loose the results of any 
:: "set" commands as soon as you execute the "endlocal" below. 
setlocal ENABLEDELAYEDEXPANSION 

::you might want 
::set "folder=%USERPROFILE%\Desktop" 
set "folder=C:\Documents and Settings\myname\Desktop" 

rem we will memorize current directory 
::If you ran this code with the current directory set to a directory on 
::a drive other than C:, your previous code would not have worked to 
:: change to your desired target directory. this slight change fixes that. 
pushd "%folder%" 

rem loop only folders with five chars within their names - unfortunately on less also 
::Use capitals for your loop variables. The var names are case sensitive, and 
::using capitals ensures there is no confusion between the var names and ~modifiers 
for /D %%G in (?????) DO (
    set checkpath="%CD%\%%G\backup" 
    if exist !checkpath! (
     for %%A in ('%%G\backup\*.*') do (
      set FileDate=%%~tA 
      set FileDate=!FileDate:~0,10! 
      rem here I want to compare file modification data with current date 
     ) 
) 
popd 
endlocal 
pause 

Но, вам не нужен «SETLOCAL» или замедленное расширение, если вы пишете так:

::you might want 
::set "folder=%USERPROFILE%\Desktop" 
set "folder=C:\Documents and Settings\myname\Desktop" 

rem we will memorize current directory 
::If you ran this code with the current directory set to a directory on 
::a drive other than C:, your previous code would not have worked to 
:: change to your desired target directory. this slight change fixes that. 
pushd "%folder%" 

rem loop only folders with five chars within their names - unfortunately on less also 
for /D %%G in (?????) DO (
    if exist "%%~G\backup" (
     for %%A in ('%%~G\backup\*.*') do (
      for /F "usebackq" %%T in ('%%~tA') do (
       echo File date is %%T, todays date is %DATE% 
      ) 
     ) 
) 
popd 
pause