Batch file 如何使用批处理删除某些文件夹
我想删除所有文件夹,这些文件夹的编号比参数中的编号高 e、 g.如果我键入Batch file 如何使用批处理删除某些文件夹,batch-file,Batch File,我想删除所有文件夹,这些文件夹的编号比参数中的编号高 e、 g.如果我键入batchname 20,批处理文件应删除名为p21,p22,p23的文件夹,并保留名为p1,p2,p3,[…],p20 我在网上找到此脚本并进行了尝试,但它只删除了除一个文件夹以外的所有内容: for /D %%D in ("*") do ( if /I not "%%~nxD"=="p%1" rd /S /Q "%%~D" ) for %%F in ("*") do ( del "%%~F" 如何使此
batchname 20
,批处理文件应删除名为p21
,p22
,p23
的文件夹,并保留名为p1
,p2
,p3
,[…]
,p20
我在网上找到此脚本并进行了尝试,但它只删除了除一个文件夹以外的所有内容:
for /D %%D in ("*") do (
if /I not "%%~nxD"=="p%1" rd /S /Q "%%~D"
)
for %%F in ("*") do (
del "%%~F"
如何使此脚本根据上述内容工作?此已注释的批处理文件可用于此任务
@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
注意:在命令rd
左侧有一个ECHO
输出到控制台,在命令提示符窗口中运行此批处理文件时将删除哪些目录。如果批处理文件在包含文件夹p1
,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/?
获取/?
goto/?
如果/?
rd/?
rem/?
设置/?
setlocal/?