批处理文件 – Windows CMD – 在for循环中设置不起作用

我想编写批处理文件,它将循环遍历包含备份目录的所有目录,并删除其中超过X天的文件.
在我想要运行我的脚本的计算机上,没有“forfile”命令.
没有Power Shell,因此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

解决方法

您需要使用延迟扩展来读取您在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

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

相关文章

Windows2012R2备用域控搭建 前置操作 域控主域控的主dns:自...
主域控角色迁移和夺取(转载) 转载自:http://yupeizhi.blo...
Windows2012R2 NTP时间同步 Windows2012R2里没有了internet时...
Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...