循环几行直到达到一个条件

Loop through several lines until a condition is reached

我有一个命令可以使用 kpscript 从 keepass 数据库中检索信息。 此命令可能会在 none 上检索 1 行、多行,但最终,它总是 returns 此输出:

OK: Operation completed successfully.

使用 PowerShell 单独处理每一行并在 StartsWith("OK:") 时退出循环的最佳方法是什么: 示例:

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

Administrator
OK: Operation completed successfully.

以下我尝试过的方法均未成功

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

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

也未成功

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

结果:

    UNAME=Administrator OK: Operation completed successfully.

重点是: UNAME=管理员 UNAME=OK:操作成功完成。 所以每一行都可以单独处理

也许这可以用数组来完成?

也未成功

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

输出相同:

    UNAME=Administrator OK: Operation completed successfully.

这是你想要做的吗?

#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 }
}

输出(使用示例输出):

UNAME=Administrator
UNAME=OK: Operation completed successfully.

老话题,但也许对某人有帮助,我就是这样解决的 使用参数 -FailIfNoEntry -FailIfNotExists 当字段为空或找不到条目时,这将为您提供以 E: *** 开头的行消息

$information 将包含一个包含有用信息的数组

$RawEntiries = & $kpscript -c:GetEntryString $PathKeepass -pw:$pscred.GetNetworkCredential().password -Field:$Field -ref-Title:"$title" -FailIfNoEntry -FailIfNotExists

If ($RawEntiries -notlike "E:*")
{
    $information = $RawEntiries[0..($RawEntiries.IndexOf("OK: Operation completed successfully.")-1)]
    $Information
}