Search code examples
powershellbatch-filevariablespowershell-2.0powershell-3.0

How to assign value to a variable in Batch file by running powershell script for it?


I have two files one is batch file named validator.bat and another one is powershell script checker.ps1

validator.bat

    @echo OFF
    set/p "pass=>"
    echo %pass%

The variable pass is to be assigned the value using powerhell script.

checker.ps1

    $pwd1 = Read-Host "Enter your passowrd: "
    $pwd2 = 'password'
    if ($pwd1 -ceq $pwd2) {
    Write-Host "matched"
    } else {
    Write-Host "differ"
    }

I want to assign the output string "matched"/"differ" to the pass variable in bat file but using only powershell script or its code. I searched a lot on Google and Youtube but I could not Find the solution to my problem. Please help me.


Solution

  • validator.bat

    @echo OFF
    for /f %%a in ('powershell -file checker.ps1') do set "pass=%%~a"
    echo %pass%
    

    checker.ps1

    $pwd1 = Read-Host "Enter your password: "
    $pwd2 = 'password'
    if ($pwd1 -ceq $pwd2) {
        Write-Host "matched"
    } else {
        Write-Host "differ"
    }
    

    Note, this will not mask the password as it's typed. You'd need to use -AsSecureString on read-host and then convert it to a regular string to compare it. There may be a way to compare secure strings that I am not aware of.