首页 > 解决方案 > 如果 Else 语句在使用 PowerShell 的 Else 端不起作用

问题描述

我在我的 powershell 脚本中使用 if else 。

if ($match.Groups.Count) {
    while ($match.Success) {
        Write-Host ("Match found: {0}" -f $match.Value)
        $match = $match.NextMatch()
    }
}
else {

    Write-Host "Not Found"
}

在 if 方面,它可以工作,但在 else 方面,它不能返回 "Not Found" 。它没有显示任何错误。

标签: powershellif-statement

解决方案


PetSerAl就像以前无数次一样,在评论中提供了关键指针:

也许令人惊讶的[System.Text.RegularExpressions.Match]是,静态[regex]::Match()方法(或其对应的实例方法)返回的实例在其属性中包含 1 个元素,.Groups即使匹配操作没有成功[1],因此,假设存储在 中的$match实例$match.Groups.Count 总是返回$true

相反,使用该.Success属性来确定是否找到了匹配项,就像您在while循环中所做的那样:

if ($match.Success) {
    while ($match.Success) {
        "Match found: {0}" -f $match.Value
        $match = $match.NextMatch()
    }
} else {
    "Not Found"
}

请注意,我已经删除了Write-Host调用,因为 Write-Host通常使用错误的工具,除非意图明确写入仅显示,从而绕过 PowerShell 的输出流,从而绕过将输出发送到其他命令的能力,将其捕获变量或将其重定向到文件。


[1][regex]::Match('a', 'b').Groups.Count返回1,即使匹配显然没有成功。


推荐阅读