Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

batch file - Windows CMD - set within for loop is not working

I want to write batch file which will loop through all directories containing backup directory and remove files older than X days within it. On computer which I want run my script there's no "forfile" command. There's no PowerShell, so CMD or VBScripts seems to be only way of accomplishing this task.

Currently I have problem with "set" statement - it seems that when I'm calling %checkpath% I didn't receive expected folder.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to use delayed expansion to read a variable that you have set inside a for loop.

Try this instead

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

Replacing the %'s with !'s on variables you have created will signal it to use delayed expansion instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...