I saw this Powershell statement in a recent Hanselminutes post -
cat test.txt | foreach-object {$null = $_ -match '<FancyPants>(?<x>.*)<.FancyPants>'; $matches.x} | sort | get-unique
I'm trying to learn Powershell at the moment and I think that I understand most of what is going on -
My understanding seems to fall down on this part of the statement -
$null = $_ -match '<FancyPants>(?<x>.*)<.FancyPants>'; $matches.x
$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? $matches.x
' returning the matches found?PowerShell $null is used as an empty placeholder to assign it to a variable, use it in comparisons. PowerShell $null is an object with null or absent value. NULL is used to represent empty or undefined. Variable hold null until you assign any value to it.
The Out-Null cmdlet sends its output to NULL, in effect, removing it from the pipeline and preventing the output to be displayed at the screen.
String to check if a string variable is null or empty in PowerShell. The IsNullorEmpty() method indicates whether the specified string is empty or null. It returns True if the string is empty and False if it is not empty. Now, let's assign a string value to a variable.
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.
'123 Main','456 Broadway'| foreach{$_; $null = $_ -match '(?<MyMatch>\d+)'; ($Matches| ft *)}
In this example you would use $Matches.MyMatch
to reference the match.
'$null=...' is used to suppress the result of the comparison. You may have seen something similar, like:
command | Out-Null
In the above, the Out-Null cmdlet is used to suppress the output. In some cases you may see this as well:
[void] (...)
Basically, all examples do the same thing, ignoring the output. If you don't use one of the above the result is going to write back to the pipeline and you may get unexpected results from commands further down in the pipeline.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With