我在批次檔中有以下 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