我有两个批处理文件(XP):
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 \ 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)。有什么想法吗?
答案 0 :(得分:2)
问题是%1和%% a的扩展,延迟扩展!被删除。
所以你应该先禁用延迟扩展
顺便说一句。删除尾部斜杠是不必要的(编辑:仅当它不是根路径时才为真)
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
)