在bat文件中的IF内执行powershell命令 - 奇怪的行为

时间:2015-06-01 19:48:56

标签: powershell batch-file

@ECHO OFF     

:: Ask for Credentials
IF NOT EXIST containers/api (
    set /p login="Enter your git username: "
    powershell -Command $pword = read-host "Enter password" -AsSecureString ; $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword) ; [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) > .tmp.txt & set /p password=<.tmp.txt & del .tmp.txt
)

上面的代码不能与错误消息一起使用:

[System.Runtime.InteropServices.Marshal] :: PtrToStringAuto($ BSTR)此时出乎意料。

没有IF的相同代码,工作得很好

@ECHO OFF     

:: Ask for Credentials

set /p login="Enter your git username: "
powershell -Command $pword = read-host "Enter password" -AsSecureString ; $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword) ; [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) > .tmp.txt & set /p password=<.tmp.txt & del .tmp.txt

我做错了什么?

1 个答案:

答案 0 :(得分:0)

好的,这就是它的工作原理

:: Ask for Credentials
IF NOT EXIST containers/webapp (
    :: Ask for Credentials
    set /p login="Enter your git username: "
    powershell -Command "$pword = read-host 'Enter password' -AsSecureString ; $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword) ; [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)" > .tmp.txt & set /p password=<.tmp.txt & del .tmp.txt 
)

然后你可以使用%password%。我用它来自动批量文件中的repo克隆。希望这有帮助