powershellpowershell-7.0automatic-variable

Why PowerShell $Matches Hashtable automatic variable is not returning all matches?


I'm using Named Captures in PowerShell. But the following example is not returning all matches. All the lines in the following code return correct output - except the lines 7 and 8. I was expecting $Matches.1 and $Matches.2 to return v and A respectively. But these two lines of code return nothing.

Question: What I may be missing here or maybe not correctly understanding here?

Ref: Lates version 7.4 of PowerShell

 PS> $string = 'The last logged on user was A\v'
 PS> $string -match 'was (?<domain>.+)\\(?<user>.+)'
 PS> $Matches.domain #returns A
 PS> $Matches.user #returns v
 PS> $Matches.count #returns 3
 PS> $Matches.0 #returns was A\v
 PS> $Matches.1 #returns nothing
 PS> $Matches.2 #returns nothing
 PS> $Matches #returns the following output
Name Value
domain A
user v
0 was A\v

Solution

  • The automatic $Matches variable is a hashtable whose entries are populated as follows:


    It follows from the above that in your case $Matches only has 'domain' and 'user' entries beyond the always-present 0 entry, because only named capture groups, with these names, are present.

    Also note that the fact that $Matches is implemented as a [hashtable] implies that its entries are inherently unordered - thus, you cannot rely on the enumeration order of the entries to be meaningful (via .GetEnumerator() for the entries as a whole, or via .Keys or .Values for the keys and values, respectively), and even the entries with keys that are conceptually indices - for the whole match and any unnamed / positional capture groups - are typically not reflected in their numerical order.


    Important considerations of $Matches use: