How do I pass an equal sign when calling a batch script in Powershell/batch?

在Windows 的 console 裡直接在參數裡使用=(等號符號), 會讓 batch file 產生跳脫, 但在 linux/macOS 世界, 就沒有這個問題, 測試用 script:

@echo off
echo 1: %1
echo 2: %2
echo 3: %3
echo 4: %4

結論, 把參數使用引號” 包起來傳就OK了.

資料來源:
https://stackoverflow.com/questions/20572424/preserving-equal-characters-in-batch-file-parameters

Call your script.bat this way:

script.bat -opt-1 -opt-2 /opt-a "/opt-b=value"

and inside script.bat, call the application this way:

rem Consume -opt-1
shift
rem Consume -opt-2
shift
rem Call the application
application %1 %~2

EDITResponse to the comments

Ok. Lets review this problem with detail.

The script.bat file below:

@echo off
rem Consume -opt-1
shift
rem Consume -opt-2
shift
rem Call the application
ECHO application %1 %~2

(please, note the ECHO command) correctly “call” the application with the second parameter including an equal-sign when its fourth parameter is enclosed in quotes, as the next screen output show:

C:\> script.bat -opt-1 -opt-2 /opt-a "/opt-b=value"
application /opt-a /opt-b=value

However, if the application IS A BATCH FILE, then it suffers from the same problem of the original script.bat file. You said that “It works well when I call the application directly from the command line”. Well, this is not true:

C:\> type application.bat
@echo off
rem ** application.bat **
echo 1: %1
echo 2: %2
echo 3: %3
echo 4: %4 

C:\> application /opt-a /opt-b=value
1: /opt-a
2: /opt-b
3: value
4:

The parameters of a Batch file may be separated by comma, semicolon or equal-sign, besides spaces and tabs. This way, if “The “=” sign in the last parameter is expected by the application”, then there is no way that the application be a Batch file and have no sense to test this method with a Batch file instead of the application.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *