Windows CMD - 在for循环中设置无效

mat*_*ked 4 cmd batch-file

我想编写批处理文件,它将循环遍历包含备份目录的所有目录,并删除其中超过X天的文件.在我想要运行我的脚本的计算机上,没有"forfile"命令.没有PowerShell,因此CMD或VBScripts似乎只是完成此任务的方法.

目前我有"设置"语句的问题 - 似乎当我调用%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
Run Code Online (Sandbox Code Playgroud)

Bal*_*i C 9

您需要使用延迟扩展来读取已在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
Run Code Online (Sandbox Code Playgroud)

%!您创建的变量替换's '将表示它使用延迟扩展.