2013-02-27 49 views
0

我遇到了以下示例的麻煩。我有一個包含文件名列表的文件。我想檢查這些文件是否存在,例如:在windows shell中運行時擴展env變量

%ProgramFiles%\Internet Explorer\iexplore.exe 
%SystemRoot%\sdfsdfsd.exe 
%SystemRoot%\explorer.exe 

每條路徑都包含環境變量。

bat文件的例子:

echo off 
for /f "tokens=*" %%a in (filelist.txt) do ( 
    if exist "%%~a" ( 
    echo %%~a exists 
) else ( 
    echo %%~a doesn't exists 
) 
) 

文件名正確加載,但我CMD無法找到的所有文件。我認爲cmd處理器不會擴展路徑中的env變量......我該怎麼做呢?或者可能還有另一個問題。

或者我怎麼能用%代替!變量和其他?

回答

2

rojo已經有了正確的想法,但是沒有必要訴諸子程序。 call也會引起嵌套變量的擴展,例如, set命令。

@echo off 

setlocal EnableDelayedExpansion 

for /f "tokens=*" %%a in (filelist.txt) do (
    call set fname=%%~a 
    if exist "!fname!" (
    echo %%~a exists. 
) else (
    echo %%~a doesn't exist. 
) 
) 

endlocal 

編輯:如@dbenham在上面的代碼延遲擴展將導致感嘆號從文件名消失指出。這可以通過在循環內移動setlocal EnableDelayedExpansion指令來減輕,並且預先將call set加上setlocal DisableDelayedExpansion以防止%fname%漏出循環。

@echo off 

for /f "tokens=*" %%a in (filelist.txt) do (
    setlocal DisableDelayedExpansion 
    call set fname=%%~a 
    setlocal EnableDelayedExpansion 
    if exist "!fname!" (
    echo %%~a exists. 
) else (
    echo %%~a doesn't exist. 
) 
    endlocal 
) 
+0

確實如此,但在腳本退出後,'call set varname'爲'%fname%'的ocd刺痛仍然被定義爲孤立的環境變量。在我看來,調用SET'會破壞'setlocal'。 – rojo 2013-02-27 23:16:57

+1

另外,延遲擴展會破壞包含'!'的任何文件名(這很少見,但我知道,但確實發生了)。這個問題可以通過在循環中打開和關閉延遲擴展來解決。 – dbenham 2013-02-28 02:00:04

+0

@rojo'call set'不會在'setlocal'內部使用時定義'%fname%'。 – 2013-02-28 07:51:24

2

嘗試使用call強制評估文本文件中的變量。

@echo off 
setlocal 
for /f "tokens=*" %%a in (filelist.txt) do (
    call :checkExists "%%~a" 
) 
goto :EOF 

:checkExists <filename> 
if exist %1 (
    echo %~1 exists 
) else (
    echo %~1 doesn't exists 
) 
goto :EOF