2

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

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

我想Test_v*.zip悄悄地删除所有内容(没有错误消息记录到屏幕上)。我可以使用以下脚本来实现这一点:

@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 . . .

当然,除非文件路径包含空格。所以在上面的例子中,如果我C:\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 . . .

我怎样才能阻止它在空间上犹豫不决?

编辑- 我已经按照 Alex K 的回答尝试了空格(加上更多的调试),看起来 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"
4

3 回答 3

2

似乎您正试图使事情变得过于复杂。

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

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

于 2012-09-19T18:28:11.917 回答
1

该函数需要单独遍历每一行,因此您需要在 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
于 2012-09-19T18:14:13.853 回答
-1

奇怪的是,这似乎有效。我已将我的版本编辑为看起来像您的版本,因此请尝试修改任何语法错误;-)

@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
于 2012-09-19T16:54:54.437 回答