Search code examples
batch-filekeepass

Batch. How to define the first line of command output into a variable?


I have a batch script that goes through a list of devices and fetches password for each of them from keepass, using KPScript. %Output% is supposed to contain the password.

KPScript command outputs:

password
OK: Operation completed successfully.

The code below echoes OK: Operation completed successfully.

@for /F "tokens=1,2,3,4 skip=1 delims=," %%A in (C:\iplist.csv) do (
    @echo I am at %%A using login %%B

    for /F "delims=" %%G in (
        '%KPSCRIPT% -c:GetEntryString %DBFILE% -pw:xxxx -Field:Password -ref-Title:%%A -refx-Group:"SSH/WEB"'
    ) do set output=%%G
    echo !output!

I have tried

  1. Using /p
) do set /p output=%%G

with this the output first echoes the password and then stops until I press Enter. When I do that, it echoes the second line of KPScript output.

  1. Using goto
) do set output=%%G & goto :done
:done
echo !output!

echo %%A

But it breaks the for loop and is unable to use variables %%A and %%B. Using files is not an option as I'm dealing with passwords.


Solution

  • @for /F "tokens=1,2,3,4 skip=1 delims=," %%A in (C:\iplist.csv) do (
        @echo I am at %%A using login %%B
        SET "output="
    
        for /F "delims=" %%G in (
            '%KPSCRIPT% -c:GetEntryString %DBFILE% -pw:xxxx -Field:Password -ref-Title:%%A -refx-Group:"SSH/WEB"'
        ) do if not defined output set "output=%%G"
        echo !output!
    )
    

    for each line in the .csv, set the content of output to nothing then execute the kpscript. This has 2 lines. output is not defined, so it's set to the password. output is now defined, so the set out... is skipped.