我应该如何传递密码(包含特殊字符)作为命令行参数?

blu*_*ker 6 windows batch-file special-characters command-line-arguments

我有一个部署脚本,我必须将LDAP密码作为cmd参数传递给我.

实际密码:(  foo\$ser"ver\\ 1 包含三个空格字符:开头,之前1和之后1)

例如

...bin>deployment.bat LDAPPassword= foo\$ser\"ver\\ 1 
Run Code Online (Sandbox Code Playgroud)

注意:密码中有空格,如开头所示.

deployment.bat呼叫到上述参数被作为参数传递的类.问题是该类接收2个不同的参数:

args[0]= foo\$ser"ver\\            //The space after \\ is omitted
args[1]=1                          //The space before and after 1 is omitted
Run Code Online (Sandbox Code Playgroud)

如何传递此密码以便将其作为单个字符串接收?

我已经尝试过引用密码了

...bin>deployment.bat LDAPPassword=" foo\$ser"ver\\ 1 "
Run Code Online (Sandbox Code Playgroud)

但它不会起作用.

jeb*_*jeb 3

您无法以任何方式转义您的密码。
由于某些带有引号和空格的组合不能放入一个参数中。

像这样"( <space><quote><space>) 即使您在周围添加一些引号,也是不可能的,即使您引用空格和引号本身。

myBat  " 
myBat " " "
myBat ^ " 
myBat ^"^ ^"^ ^"
Run Code Online (Sandbox Code Playgroud)

最好将密码中的所有引号加倍,并将密码括在引号中。
然后您可以毫无问题地使用所有其他字符。

部署.bat“foo\$ser\”“ver\1”

并在deployment.bat中

@echo off
setlocal DisableDelayedExpansion
set "pwd=%~1"
setlocal EnableDelayedExpansion
set "pwd=!pwd:""="!"
echo pwd='!pwd!'
Run Code Online (Sandbox Code Playgroud)

您应该仅使用延迟扩展的密码,以避免特殊字符出现问题。

要访问命令行参数,您还可以查看
SO:如何接收最奇怪的命令行参数?