2008-12-15 81 views
2

閱讀stackoverflow上的現有文章,並在網上進行了一些閱讀。我認爲是在我失去太多頭髮之前發佈我的問題的時候了!Windows批處理文件 - ENABLEDELAYEDEXPANSION查詢

我有一個批處理文件,我雙擊運行中下面的代碼,在Windows XP SP3:

SETLOCAL ENABLEDELAYEDEXPANSION 

::Observe variable is not defined 
SET test 

::Define initial value 
SET test = "Two" 

::Observe initial value is set 
SET test 

::Verify if the contents of the variable matches our condition 
If "!test!" == "Two" GOTO TWO 

::First Place holder 
:ONE 

::Echo first response 
ECHO "One" 

::Second Place holder 
:TWO 

::Echo second response 
ECHO "Two" 

::Await user input 
PAUSE 

ENDLOCAL 

基本上我試圖建立,如果我可以通過我的腳本中使用條件語句導航。似乎很明顯,我在變量範圍和延遲變量擴展方面遇到了一些問題,但我在做錯的時候有點失落。

任何人都可以指向正確的方向嗎?

回答

5

立即解決問題是,你該變量的值設置爲<「兩課」>,你可以在這裏看到:

@echo off 

SETLOCAL ENABLEDELAYEDEXPANSION 

::Observe variable is not defined 
SET test 

::Define initial value 
SET test = "Two" 

::Observe initial value is set 
SET test 
echo %test% 
echo..%test %. 

::Verify if the contents of the variable matches our condition 
If "!test!" == "Two" GOTO TWO 

::First Place holder 
:ONE 

::Echo first response 
ECHO "One" 

::Second Place holder 
:TWO 

::Echo second response 
ECHO "Two" 

::Await user input 
PAUSE 

ENDLOCAL 

主要生產:

Environment variable test not defined 
test = "Two" 
. "Two". 
"One" 
"Two" 
Press any key to continue . . . 

的原因,你的「 set test「輸出變量的原因與」set t「的原因相同 - 如果沒有特定名稱的變量,它將輸出以該名稱開頭的所有變量。

set命令也是一個挑剔的小野獸,不喜歡'='字符周圍的空格;它將它們(和方式中的引號)合併到環境變量名稱和分配給它的值中。相反,使用:

set test=Two 

此外,如果您使用延遲擴展,自%test%和!test以來無所謂!將擴大相同。它是有用的喜歡的語句:

if "!test!" == "Two" (
    set test=TwoAndABit 
    echo !test! 
) 

內回聲將輸出TwoAndABit而%的測試%,當if語句遇到整,會使其輸出兩個被擴大。

不過,爲了保持一致性,我總是使用延時擴展。

+0

感謝明確闡述響應大同!所有的閱讀,測試和解決我的結局:) – 2008-12-15 11:50:50

0

SET命令通過最後一個非空字符取等號後的所有內容。你的命令

SET test = "Two" 

...是可變的測試與領先的空白和引號,不只是兩個字符串設定爲數值「2」。

所以,當你測試...

If "!test!" == "Two" GOTO TWO 

你真的測試...

If " "Two"" == "Two" GOTO TWO