当path包含空格时,如何使用通配符从MS DOSbatch file中删除多个文件?

说我有一个目录,其中包含以下文件:

Test.bat Test_a.txt Test_b.txt Test_v1.zip Test_v2.zip Test_v3.zip

我想静静地删除所有的Test_v*.zip (没有错误消息logging到屏幕上)。 我可以用下面的脚本实现这个function:

 @ECHO OFF SET OLD_ZIPS=^ C:\Tmp\Test_v*.txt;^ C:\Tmp\Test_a.txt ECHO Deleting the following files: %OLD_ZIPS% FOR %%Y IN (%OLD_ZIPS%) DO ( IF EXIST %%Y ( ECHO Deleting %%Y DEL /Q %%Y) ) PAUSE 

这工作正常:

 Deleting the following files: C:\Tmp\Test_v*.txt;C:\Tmp\Test_a.txt Deleting "C:\Tmp\Test_v1.txt" Deleting "C:\Tmp\Test_v2.txt" Deleting "C:\Tmp\Test_a.txt" Press any key to continue . . . 

除非文件path中包含空格。 所以在上面的例子中,如果我C:\Tmp with spaces\Test_v*.txtC:\Tmp\Test_v*.txt更改为C:\Tmp with spaces\Test_v*.txt我会得到:

 Deleting the following files: C:\Tmp test\Test_v*.txt;C:\Tmp test\Test_a.txt Press any key to continue . . . 

我怎样才能阻止它在空间处堵塞?

编辑 – 我已经试过空格按照亚历克斯K的答案(加上多一点debugging),它看起来也许for循环不分裂的事情,因为我期望:

 @ECHO OFF SET OLD_ZIPS=^ C:\Tmp test\Test_v*.txt;^ C:\Tmp test\Test_a.txt ECHO Deleting the following files: %OLD_ZIPS% FOR %%Y IN (%OLD_ZIPS%) DO ( ECHO Checking existance of "%%Y" IF EXIST "%%Y" ( ECHO Deleting "%%Y" DEL /Q "%%Y") ) PAUSE 

..给我:

 Deleting the following files: C:\Tmp test\Test_v*.txt;C:\Tmp test\Test_a.txt Checking existance of "C:\Tmp" Checking existance of "C:\Tmp" Checking existance of "test\Test_a.txt" 

Solutions Collecting From Web of "当path包含空格时,如何使用通配符从MS DOSbatch file中删除多个文件?"

该函数需要逐行循环遍历每一行,因此您需要在FOR循环中引用该变量,用分号将其标记,然后清洗并重复。

 @ECHO OFF SET OLD_ZIPS=^ C:\tmp with spaces\Test_v*.txt;^ C:\tmp\Test_a.txt ECHO Deleting the following files: %OLD_ZIPS% :deleteFiles for /f "tokens=1* delims=;" %%A in ("%OLD_ZIPS%") do ( ECHO Checking existance of "%%A" IF EXIST "%%A" ( ECHO Deleting "%%A" DEL /Q "%%A" ) set OLD_ZIPS=%%B ) if not "%OLD_ZIPS%" == "" goto :deleteFiles PAUSE 

似乎你正试图把事情复杂化。

 for %a in ("C:\Tmp with spaces\Test_v*.txt" "C:\Tmp\Test_a.txt") do del /q "%a" 

做你想要的,并且可以从命令行输入。 如果要在批处理文件中执行,请将%a更改为%% a

奇怪的是,这似乎工作。 我已经编辑我的版本看起来像你的,所以请尝试和修改任何语法错误;-)

 @ECHO OFF SET OLD_ZIPS="C:\Tmp with spaces\Test_v*.txt";^ "C:\Tmp with spaces\Test_a.txt"; ECHO Deleting the following files: %OLD_ZIPS% FOR %%Y IN (%OLD_ZIPS%) DO ( IF EXIST %%Y ( ECHO Deleting %%Y DEL /Q %%Y) ) PAUSE