-1

I have the following for loop inside batch file:

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

)

And I always get the following error: [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)"" was unexpected at this time.

When I run the command outside the for loop, it works.

What is wrong?

  • 2
    Why on earth would you mix a batch with a PowerShell and not just use a PowerShell script directly? For one your quotes are off. You have a pair for set and one for the -Command and they're probably canceling each other. – Seth Sep 20 '16 at 10:01
  • it works outside the for loop so I assume that quotes are not the issue here – user1563721 Sep 20 '16 at 10:24
  • How do you run the command outside the for loop? What about placing the command between single quotes and Enter Password2 between double quotes? – Lieven Keersmaekers Sep 20 '16 at 10:28
2

The issue is that the for loop thinks that the end bracket is inside the powershell command.

The possible solution is to create a function and call it from the loop:

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
  • +1, Not how I would solve the issue, but you have properly diagnosed the source of the reported error. – dbenham Sep 20 '16 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.