我做了一個批處理程序以遞歸方式在目錄中執行一些簡單的任務,並且它通常沒有問題。但如果目錄名稱包含「&」,則出現錯誤。當目錄名稱包含「&」時,批處理文件在目錄中執行任務
@echo off
setlocal enableextensions disabledelayedexpansion
set "exitCode=0"
set "BaseDir=%~1"
if not defined BaseDir set "BaseDir=%CD%"
for %%f in ("%BaseDir%") do set "BaseDir=%%~ff"
if not exist "%BaseDir%" (
call :error "Base directory does not exist"
goto endProcess
)
call :recursive "%BaseDir%"
if errorlevel 1 set "exitCode=1"
goto :endProcess
:Whattodo
echo %CD%
goto :eof
:recursive BaseDir
setlocal
set "BaseDir=%~f1"
pushd "%BaseDir%"
for /d %%d in (*) do if not errorlevel 1 call :recursive "%%~fd"
call :Whattodo
popd
endlocal
goto :eof
:error
echo(%~1
set "exitCode=1" & cmd /d /q /c exit /b 1
goto :eof
:endProcess
endlocal & exit /b %exitCode%
我會得到一個輸出這樣的:
C:\tmp\01\04
C:\tmp\01\05
C:\tmp\01
C:\tmp\02\06
C:\tmp\02\07\08
C:\tmp\02\07
C:\tmp\02
C:\tmp\03
C:\tmp
,但如果我有一個目錄像這樣的 「C:\ tmp目錄\ 02 \ 06 &一個」 我也會有這種輸出
C:\tmp\01\04
C:\tmp\01\05
C:\tmp\01
C:\tmp\02\06
'a' is not recognized as an internal or external command,
C:\tmp\02
C:\tmp
我知道問題出在下面一行,但我不知道如何解決它。
for /d %%d in (*) do if not errorlevel 1 call :recursive "%%~fd"
!!編輯
在我發佈之前,我嘗試了我可以調試的錯誤。 echo %CD%
只是打印當前目錄,以幫助我調試。可能是cd
,錯誤將會持續。 (我試過)
我能發現,變量"%%~fd"
已擴展,並且比行正在處理。 這樣呼叫傳遞"C:\tmp\02\06"
(而不是"C:\tmp\02\06 & a"
),並嘗試execult命令a
問題出現在你的':Whattodo'子程序中嗎?嘗試用'cd'替換'echo%CD%',看看是否可以擺脫錯誤。 – rojo 2014-11-22 03:09:42