2010-08-12 44 views
3

我想傳遞一個空格分隔變量到像一個批處理文件:如何將空格分隔的變量傳遞給bat文件?

c:\applications\mi_pocess.bat A1 1AA 

當我運行echo %1mi_process返回A1

我怎麼會去它承認A1 1AA是一個字符串?

我已經試過它環繞在我的外部軟件雙引號像

c:\applications\mi_pocess.bat + chr$(34) + A1 1AA + Chr$(34) 

echo %1現在返回"A1 1AA"(我不想在變量引號)

感謝

+0

你感謝2人,現在,他們已經回答了你的問題?如果是,請接受答案。 – 2013-03-07 01:50:19

回答

0

這是向批處理文件發送包含空格的值的唯一方法,因此如果不需要引號,則必須在批處理文件中將其刪除。

3

我確定您知道%1,%2等等.bat內代表傳遞給命令行上.bat的編號參數。

如果您使用它們作爲%~1,%~2等,則所有的周圍引號將自動刪除,如果它們在那裏。

考慮這個space-in-args.bat來進行測試:

@echo off 
echo. %1 
echo. (original first argument echo'd) 
echo. 
echo. "%1" 
echo. (original first argument with additional surrounding quotes) 
echo. 
echo. %~1 
echo. (use %%~1 instead of %%1 to remove surrounding quotes, should there be) 
echo. 
echo. "%~1" 
echo. (we better use "%%~1" instead of "%%1" in this case: 
echo.  1. ensure, that argument is quoted when used inside the batch; 
echo.  2. avoid quote doubling should the user have already passed quotes. 
echo. 

運行:

space-in-args.bat "a b c d e" 

輸出是:

"a b c d e" 
    (original first argument echo'd) 

""a b c d e"" 
    (original first argument with additional surrounding quotes) 

    a b c d e 
    (using %~1 instead of %1 removes surrounding quotes, should there be some) 

"a b c d e" 
    (we better use "%~1" instead of "%1" in this case: 
     1. ensure, that argument is quoted when used inside the batch; 
     2. avoid quote doubling should the user have already passed quotes. 

參見for /?(向下滾動接近年底)來找出關於更多這些轉換。

+0

謝謝皮皮塔斯 - 這很好地解釋它 – Mark 2010-08-13 06:55:42

1

要麼你想在批處理文件使用%~1

echo %1 
echo %~1 

產量:

> test "A1 AA1" 
"A1 AA1" 
A1 AA1 

因爲%~1刪除從參數報價。

如果您永遠不會期望超過一個參數,那麼另一種選擇是%*%*包含批處理文件的所有參數。這將使您避免使用此引號,但它也意味着,如果你想給另一個說法,不應該是你目前正在期待一個部分,你的運氣了:

echo %* 

然後得出:

> test2 A1 AA1 
A1 AA1 
+0

謝謝Johannes。現在在我的處理中執行類似的操作 – Mark 2010-08-13 06:56:13

0

你應該使用%*獲得除%0

sended所有參數,如果你調用一些批處理文件這樣 call some bat 54 12 33

與代碼

set params=%* 
echo Params goted : %params% 

則回覆:

Params goted : 54 12 33