需要Windows cmd shell脚本的帮助

时间:2013-12-09 10:44:07

标签: windows batch-file recursion cmd directory

我有以下脚本从ROOT目录中删除所有子目录,并删除ROOT目录中除* .bat文件之外的所有文件。

pause
FOR /R C:\Temp\ %%F IN (*.*) DO IF NOT "%%~xF" == ".bat" DEL /F /S "%%F"
for /d %%i in ("c:\Temp\*") do rmdir /s /q "%%i"
pause

帮助我改进脚本,它还可以扫描ROOT子目录中的文件* .bat并删除所有带有其他扩展名的文件。

1 个答案:

答案 0 :(得分:0)

测试。如果它在控制台中显示的内容是需要执行的操作,请从保留echormdir命令的破坏性行中删除del命令。

@echo off

    setlocal enableextensions

    set "root=c:\temp"

    rem For the %root% tree
    for /r "%root%" %%d in (.) do (

        rem Test for the presence of .bat files under directory 
        dir /s /b "%%~fd\*.bat" 2>nul | find /v "" > nul 
        if errorlevel 1 (

            rem If there is no .bat files under directory, remove directory
            echo(**** rmdir /s /q "%%~fd"

        ) else (

            rem There are bat files in directory or under it. Remove anything else in this directory
            for %%f in ("%%~fd\*") do if not "%%~xf"==".bat" echo(-------- del "%%~ff"

        )

    )

已编辑 - 要适应评论 - 如何调整代码以便处理多个根文件夹?获取代码并将其转换为子例程,然后使用相应的根调用它。迭代根目录列表

@echo off

    setlocal enableextensions

    for %%r in ("c:\temp" "c:\temp2" "c:\temp3") do call :processRoot %%r

    endlocal
    exit /b

:processRoot
    setlocal enableextensions disabledelayedexpansion

    set "root=%~1"

    rem For the %root% tree
    for /r "%root%" %%d in (.) do (

        rem Test for the presence of .bat files under directory 
        dir /a /s /b "%%~fd\*.bat" 2>nul | find /v "" > nul 
        if errorlevel 1 (

            rem If there is no .bat files under directory, remove directory
            echo(**** rmdir /s /q "%%~fd"

        ) else (

            rem There are bat files in directory or under it. Remove anything else in this directory
            for %%f in ("%%~fd\*") do if not "%%~xf"==".bat" echo(-------- del "%%~ff"

        )

    )
    endlocal
    goto :eof