Job
Job

Reputation: 505

If Else Statement is not working in Else side using PowerShell

I use if else in my powershell script.

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

    Write-Host "Not Found"
}

in the if side, it works, but in the else side, It cannot return "Not Found" . It does not show any error.

Upvotes: 0

Views: 149

Answers (1)

mklement0
mklement0

Reputation: 440162

PetSerAl, as countless times before, has provided the crucial pointer in a comment:

Perhaps surprisingly, the [System.Text.RegularExpressions.Match] instance returned by the static [regex]::Match() method (or its instance-method counterpart) contains 1 element in its .Groups property even if the matching operation didn't succeed[1], so that, assuming an instance stored in $match, $match.Groups.Count always returns $true.

Instead, use the .Success property to determine if a match was found, as you already do in the while loop:

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

Note that I've removed the Write-Host calls, because Write-Host is generally the wrong tool to use, unless the intent is explicitly to write to the display only, thereby bypassing PowerShell's output streams and thus the ability to send the output to other commands, capture it in a variable or redirect it to a file.


[1] [regex]::Match('a', 'b').Groups.Count returns 1, even though the match clearly didn't succeed.

Upvotes: 3

Related Questions