如何使用批删除某些文件夹

时间:2018-06-05 10:32:59

标签: batch-file

我想删除所有文件夹,这些文件夹的编号大于参数中的编号。

e.g。如果我输入Cells(rowselect, 5) = IIf(Me.Option1.Value, "Option 1", IIf(Me.Option2.Value, "Option 2", "Option 3")) ,批处理文件应删除名为batchname 20p21p22的文件夹,并保留名为p23的文件夹, p1p2p3[...]

我发现这个脚本在线并尝试了,但它只删除了除一个文件夹之外的所有内容:

p20

如何根据上述内容使此脚本正常工作?

1 个答案:

答案 0 :(得分:0)

此评论的批处理文件可用于此任务。

@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只输出到控制台,在命令提示符窗口中运行此批处理文件时将删除哪些目录。如果批处理文件在包含文件夹ECHOp1,...... {/ p>的目录中按预期正常工作,则通过启动具有各种编号的批处理文件来验证后删除命令p2

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

@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 /?