当我们传参数引用“(双引号)

我已经写了下面的脚本,要求用户input密码作为参数,如果我input密码"Hello&123"失败,但它正在为其他情况下工作!Hello&123>请提出一些好方法来克服这种情况。

TestScript1.bat

 @echo off setlocal set "psCommand=powershell -Command "$pword = read-host 'Enter password:' -AsSecureString ; ^ $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^ [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)"" for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p if "%password%" == "" @echo password cannot be empty & goto DIE TestScript2.bat.bat testuser "192.168.1.1" "%password%" endlocal :DIE exit /b 1 

TestScript2.bat

 @echo off echo n | psftp %1@%2 -pw %3 -b Test3.bat >> TestLog.log 2>&1 

当您尝试展开变量时,您需要使用延迟扩展。
对于任何内容,延迟扩展都是安全的。
但是由于延迟扩展,感叹号和插入符号存在问题。
这就是为什么你应该在set "password=%%p"之后启用它。

 @echo off setlocal DisableDelayedExpansion set "psCommand=powershell -Command "$pword = read-host 'Enter password:' -AsSecureString ; ^ $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^ $str=[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR); ^ Write-host('#'+$str)"" for /f "usebackq delims=" %%p in (`%psCommand%`) do set "password=%%p" setlocal EnableDelayedExpansion set "password=!password:*#=!" if not defined password ( echo password cannot be empty goto :DIE ) echo It works: pwd=!password! TestScript2.bat testuser "192.168.1.1" "!password!" 

但是你将得到TestScript2.bat的下一个问题,因为扩展本身是安全的,但是你不能通过值传递一个任意的密码到一个函数或批处理文件(这是不可能的)。

所以你应该通过参考而不是价值来转移它。

 TestScript2.bat testuser "192.168.1.1" password 

再用!%~3! 〜3在TestScript2.bat中使用它!%~3!

但是用密码调用psftp命令会导致再次出现任意值的问题。
您需要将内容转换为安全格式,在这种情况下,您必须考虑psftp的规则。
我测试过,psftp替换\"""

TestScript2.bat

 @echo off setlocal EnableDelayedExpansion set "password=!%~3!" set "password=!password:"=\""!" ... more replace rules echo n | psftp %1@%2 -pw "!password!" -b Test3.bat >> TestLog.log 2>&1 

我想你想要的是这样的:

 SET Test="Hello" FOR /F "TOKENS=2 DELIMS==" %a in ('SET Test') DO @ECHO %~a 

%〜a删除任何引号。

&符号和>都将需要转义( !Hello^&123^> ),因为它们当前不是%3被接收为!Hello

你可以使用延迟扩展来解决这个问题:

 setlocal enableDelayedExpansion TestScript2.bat testuser "192.168.1.1" !password!