Try the following:
$content = Get-Content $outputfilePath ($content -match $regex).Count
Powershell has a number of comparison operators that are likely to make your life easier. Here is a quick list:
-eq -ne -gt -ge -lt -le -Like -NotLike -Match -NotMatch -Contains -NotContains -In -NotIn -Replace
In this case, -Match
will match the string $ content for your regular expression $ regex, and the result is grouped in parentheses. This grouping is a collection of strings. Then we can count the objects and print the exact number of matches.
So why is your code working as expected? When you have one match, .Matches
actually returns a System.Text.RegularExpressions.Match object, which looks something like this for the string "test123":
Groups : {test123} Success : True Captures : {test123} Index : 15 Length : 7 Value : test123
Why is this happening? Because the Microsoft.PowerShell.Commands.MatchInfo object returns a Select-String
. You can verify this by doing some other properties, such as .Filename
in the output with a single match.
Ok, but why can't we get all our matches at once? This is because multiple matches return multiple objects, so now you have a collection in which you are trying to work. The collection is of a different type and does not understand .Matches
. No collection is returned in 1 match, but instead there is one object that understands .Matches
!
In short: these are not the results you are looking for!
source share