我在批处理文件中有以下 for 循环:
for /l %%x in (1, 1, %k%) do (
set "psCommand=powershell -Command "$pword = read-host 'Enter Password2' -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
)
我总是收到以下错误: [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)"" 此时是意外的。
当我在 for 循环外运行该命令时,它可以起作用。
怎么了?
答案1
问题是 for 循环认为结束括号位于 powershell 命令内。
可能的解决方案是创建一个函数并从循环中调用它:
for /l %%x in (1, 1, %k%) do (
call :getPassword password
)
:getPassword
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
EXIT /B 0