2011-03-07 173 views
3

我有两个批处理文件(XP):在批处理文件中使用SetDelayedExpansion:处理包含!的目录/文件名!

下的test.bat:

setlocal EnableDelayedExpansion 

rem check for argument 
if [%1]==[] goto :noarg 

:arg 
rem check for trailing backslash and remove it if it's there 
set dirname=%1 
IF !dirname:~-1!==\ SET "dirname=!dirname:~0,-1!" 

rem find all log files in passed directory and call test2.bat for each one 
for /f "tokens=* delims= " %%a in ('dir !dirname!\*.log /s /b') do call test2.bat "%%a" 

goto :finish 

:noarg 
rem prompt for directory to scan 
set /p dirname=Type the drive or directory, then hit enter: 

rem loop if nothing entered 
if [!dirname!]==[] goto :noarg 

rem check for trailing backslash and remove it if it's there 
IF !dirname:~-1!==\ SET "dirname=!dirname:~0,-1!" 

rem find all log files in passed directory and call test2.bat for each one 
for /f "tokens=* delims= " %%a in ('dir "!dirname!"\*.log /s /b') do call test2.bat "%%a" 

goto :finish 

:finish 

test2.bat:

echo %1 

证明了问题:

- 创建称为目录c:\ test,另一个叫做c:\ test!并在每个目录中放置一个空的test.log文件。

然后运行:

test c:\test 

可正常工作(test2.bat回声 “C:\测试\ test.log中”)

现在运行:

test c:\test! 

问题是test2.bat回应“c:\ test \ test.log”而不是所需的“c:\ test!\ test.log”)

我意识到这是因为!被保留用于EnableDelayedExpansion使用。但是,如果解决方案是“用%扩张”,那么我挂,因为我需要使用DelayedExpansion(每Handling trailing backslash & directory names with spaces in batch files

我周围戳:

setlocal DisableDelayedExpansion 

endlocal 

How can I escape an exclamation mark ! in cmd scripts?

没有运气(可能是PEBCAK)。

有什么想法?

回答

2

问题是%1和%% a的扩展,带有延迟扩展!已移除。
所以你应该先禁用延迟扩展。
Btw。删除尾部斜线不是必需的(编辑:只有真实,如果它不是根路径)

setlocal DisableDelayedExpansion 

rem check for argument 
if "%~1"=="" goto :noarg 

:arg 
set "dirname=%~1" 

rem find all log files in passed directory and call test2.bat for each one 
for /f "tokens=* delims=" %%a in ('dir "%dirname%\*.log" /s /b') do (
    set "file=%%~a" 
    setlocal EnableDelayedExpansion 
    echo found #!file!# 
    call test2.bat "!file!" 
    endlocal 
) 
+0

再次感谢@jeb!就在我想我正在摸索一些东西时...... 你介意解释为什么我不需要去掉尾随的反斜杠吗?我正在处理,例如,一个用户传递c:\ - 这使得for/F行出错,因为:'“c:\\ *。log”' – 2011-03-08 17:38:43

+0

@Craig H:你说得对,它不适用于根目录,但在任何其他像c:\ temp \\ *。log(我只测试第二种情况) – jeb 2011-03-08 19:50:17

+0

感谢澄清 - 只是想看看我是否忽略了一些东西。再次感谢您的帮助! – 2011-03-09 05:52:42

相关问题