【问题标题】:How to delete certain folders using batch如何使用批处理删除某些文件夹
【发布时间】:2018-06-06 13:52:17
【问题描述】:

我要删除所有文件夹,标记的数字比参数中的大。

例如如果我键入batchname 20,批处理文件应删除名为p21p22p23 的文件夹并保留名为p1p2p3、@987654328 的文件夹@,p20

我在网上找到了这个脚本并尝试过,但它只删除了一个文件夹以外的所有内容:

for /D %%D in ("*") do (
    if /I not "%%~nxD"=="p%1" rd /S /Q "%%~D"
)
for %%F in ("*") do (
    del "%%~F"

如何使这个脚本按照上面的方法工作?

【问题讨论】:

  • 您需要从文件夹名称中分离出数字并将其分配给变量。这可以通过 SET 命令来完成。然后就可以用 IF 命令进行比较了。

标签: batch-file


【解决方案1】:

此注释批处理文件可用于此任务。

@echo off
rem Is the batch file not called with at least one parameter?
if "%~1" == "" goto :EOF

rem Is the parameter string not a positive number?
for /F "delims=0123456789" %%I in ("%~1") do goto :EOF

rem Convert the number string to an integer and back to a number string
rem using an arithmetic expression and then check for equal strings. A
rem difference means that the number string was not in valid range of
rem 0 to 2147483647 or was with leading zeros resulting in interpreting
rem the number as octal number on conversion to integer.

set /A Number=%~1 2>nul
if not "%~1" == "%Number%" set "Number=" & goto :EOF

rem Search for non hidden directories in current directory starting
rem with letter P. For each found directory matching this simple
rem wildcard pattern use an arithmetic expression to convert the
rem number string without first character P to an integer and back
rem to a number string. Then compare case-insensitive the original
rem directory name with rebuild directory name to make sure that the
rem found directory has a name consisting really of just letter P and
rem a decimal number in range 0 to 2147483647 without leading zeros.
rem If this condition is true, compare the two numbers using an integer
rem comparison and remove the directory quietly and with all files and
rem subdirectories on having a number greater than the parameter number.

setlocal EnableDelayedExpansion
for /D %%I in (p*) do (
    set "Number=%%I"
    set /A Number=!Number:~1! 2>nul
    if /I "p!Number!" == "%%I" if !Number! GTR %~1 ECHO rd /Q /S "%%I"
)
endlocal

注意:还有一个ECHO 用于命令rd 以输出到控制台,在命令提示符窗口中运行此批处理文件时将删除哪些目录。如果批处理文件在包含文件夹p1p2,...的目录中确实按预期工作,则在验证后删除命令ECHO,以各种数字启动批处理文件。

这也是在批处理文件中使用的单命令解决方案,无需任何有效性检查,也无需使用延迟的环境变量扩展。它比上面的脚本更快,但也更容易出错,在我看来这对递归删除文件夹不利。

@for /D %%I in (p*) do @for /F "delims=Pp" %%J in ("%%I") do @if %%J GTR %~1 ECHO rd /Q /S "%%I"

再次需要删除命令ECHO 才能真正删除编号大于作为第一个参数传递给批处理文件的编号的子目录。

要了解所使用的命令及其工作原理,请打开命令提示符窗口,在其中执行以下命令,并仔细阅读每个命令显示的所有帮助页面。

  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • rd /?
  • rem /?
  • set /?
  • setlocal /?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2021-04-06
    相关资源
    最近更新 更多