0

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.

1 Answers1

0
@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.

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • Works for the first line of .csv butt on the second line, the output is `OK: Operation completed successfully.` Edit: no wait, seems to work when I put `set "output="` outside the first loop. – makesaltnotsugar May 10 '23 at 12:44
  • All I can say is that moving the `set "output="` outside of the `for...%%A` loop should not act in this manner. Unfortunately, I cannot test it as I don't have access to the database/csv/kpscript involved. `Output` should be set to *nothing* just before the `for...%%G` loop. It *could* occur if the extracted password was empty for the instances after the first line of the `.csv` since the `for/f` would skip empty lines. – Magoo May 10 '23 at 19:12
  • Ah actually you are right. I forgot that KPScript is looking for passwords with variables set from .csv and as I was using just demo keepass .kdbx file, kpscript did not fetch any passwords. Thank you for your help. – makesaltnotsugar May 11 '23 at 05:29