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.
$matchcontains, the code works for me. If you ever enter thatifblock, you are never going to enter theelseblock no matter how many times you use.NextMatch()without a loop outside of theif/elseor calling this entire code block again separately. If the goal is to assign$matchsomewhere above and expect an output of "Match found: , Match found: ....Not found," it can't happen without entering that code block again on another iteration.[regex]::Match('a', 'b').Groups.Count.