UPDATE: the core of this question is (of course SO has seen this before) a duplicate. But I'll leave this answer because the OP had multiple other issues in his code.
There are a couple of things wrong with your code:
- you cannot use batch line continuations (^) inside the PowerShell code
- you must write your password to stdout from inside your PowerShell code, or it will simply not be "seen" by the surrounding batch file code
- You cannot get the output (see above point) by using
| set /P var=
. If you want to this, use a the batch for
syntax.
Putting this all together, you could come up with something like this:
@rem might want to put this here, to reduce output clutter.
@echo off
@rem store PowerShell code in batch variable for better handling
@rem note the Write-Host at the end of the PowerShell code to output the password.
set psargs=$pword = Read-Host -Prompt 'Enter Password' -AsSecureString;
set psargs=%psargs% $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword);
set psargs=%psargs% $password=[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR);
set psargs=%psargs% Write-Host $password
@rem call PowerShell and get the output into the batch variable "password".
for /F usebackq %%i in (`powershell -NoProfile -Command "%psargs%"`) do (
set password=%%~i
)
@rem do your test.
if "%password%" == "test" (
echo hi
timeout /t 2
) else (
echo Invalid password.
timeout /t 2
exit
)
Other ways to achieve the same are also possible. For example, you could also test your password inside the PowerShell code and use exit 1
or exit 0
to signal to the batch code (using if %ERRORLEVEL% ...
) if the password was correct or not. Or simply write the whole script in PowerShell in the first place.