powershellkeepass

Loop through several lines until a condition is reached


I have a command to retrieve info from a keepass database using the kpscript. This command may retrieve 1 line, multiple line on none, but, in the end, it always returns this output:

OK: Operation completed successfully.

What is the best way to handle each line individually with PowerShell and exit the loop if StartsWith("OK:"): Example:

KPScript -c:GetEntryString $PASSHOME\$PASSFILE -pw:$PASS -Field:UserName $SEARCH

Administrator
OK: Operation completed successfully.

Following approaches I have tried unsuccessfully

$UNAME = KPScript -c:GetEntryString $PASSHOME\$PASSFILE -pw:$PASS -Field:UserName $SEARCH 
IF(! $UNAME){ 
    write-host "UNAME1=$UNAME" 
    write-host "ERROR UNAME" -foreground "red" 
    exit 
}

and

while (! $UNAME) { KPScript -c:GetEntryString $PASSHOME\$PASSFILE -pw:$PASS -Field:UserName $SEARCH }

Also unsuccessful

    $UNAME=KPScript -c:GetEntryString $PASSHOME\$PASSFILE -pw:$PASS -Field:UserName $SEARCH
    write-host "UNAME=$UNAME"

The result:

    UNAME=Administrator OK: Operation completed successfully.

The point is to have: UNAME=administrator UNAME=OK: Operation completed successfully. So every line can be treated individualy

Maybe this be accomplished with an array?

Also unsuccessful

    $UNAME=@(KPScript -c:GetEntryString $PASSHOME\$PASSFILE -pw:$PASS -Field:UserName $SEARCH)
    write-host "UNAME=$UNAME"

Output is the same:

    UNAME=Administrator OK: Operation completed successfully.

Solution

  • Is this what you're trying to do?

    #Sample of kpscript output
    #$output = "Administrator","OK: Operation completed successfully.","Should have stopped already"
    
    $output = KPScript -c:GetEntryString $PASSHOME\$PASSFILE -pw:$PASS -Field:UserName $SEARCH
    
    foreach ($line in $output) {
        $UNAME = $line
        Write-Host "UNAME=$UNAME"
        if($line.StartsWith("OK:")) { break }
    }
    

    Ouptut (using the sample-output):

    UNAME=Administrator
    UNAME=OK: Operation completed successfully.