2011-03-07 178 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

相關問題