Question:
I saw this Powershell statement in a recent Hanselminutes post –
1 2 |
cat test.txt | foreach-object {$null = $_ -match ' |
I’m trying to learn Powershell at the moment and I think that I understand most of what is going on –
- The statement loops through each line of ‘test.txt’ and runs a regex against the current line
- All the results are collated and then sorted and duplicates removed
My understanding seems to fall down on this part of the statement –
1 2 |
$null = $_ -match ' |
- What is the ‘
$null =
‘ part of the code doing, I suspect this is
to handle a scenario when no match is returned but I’m not sure how
it works? - Is ‘
$matches.x
‘ returning the matches found?
Answer:
Yes, the -match
operator results in True
or False
; assigning to $null
suppresses the output.
The (?<>)
regex syntax creates a capture group. In this case it’s creating a capture group called x
for any characters between <FancyPants>
and <.FancyPants>
. $matches
contains the match info for the last match. Capture groups can be referenced by $matches.CaptureGroupName
.
Here is an example you can use to see what is in the $Matches
variable.
1 2 |
'123 Main','456 Broadway'| foreach{$_; $null = $_ -match '(? |
In this example you would use $Matches.MyMatch
to reference the match.