'$ null =' in powershell

I saw this Powershell expression in a recent Hanselminutes post -

cat test.txt | foreach-object {$null = $_ -match '<FancyPants>(?<x>.*)<.FancyPants>'; $matches.x} | sort | get-unique 

I am trying to learn Powershell at the moment, and I think I understand most of what is happening -

  • A statement goes through each line of "test.txt" and runs a regular expression for the current line
  • All results are sorted, and then duplicates are sorted and deleted.

My understanding seems to fall on this part of the statement -

 $null = $_ -match '<FancyPants>(?<x>.*)<.FancyPants>'; $matches.x 
  • What is the " $null = " part of the code, I suspect it is to handle the script when the match does not return, but I'm not sure how it works?
  • Are there any $matches.x return matches?
+6
source share
2 answers

Yes, the -match operator results in True or False ; assigning $null suppresses the output.

The regex (?<>) Syntax creates a capture group. In this case, it creates a capture group called x for any characters between <FancyPants> and <.FancyPants> . $matches contains match information for the last match. Capture groups can be referenced in $matches.CaptureGroupName .

Here is an example that 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 should use $Matches.MyMatch to refer to a match.

+8
source

'$ null = ...' is used to suppress the comparison result. You may have seen something similar, for example:

 command | Out-Null 

In the above example, the Out-Null cmdlet is used to suppress output. In some cases, you can also see this:

 [void] (...) 

Basically, all the examples do the same, ignoring the conclusion. If you do not use one of the above, the result will be written back to the pipeline, and you can get unexpected results from the commands further in the pipeline.

+5
source

Source: https://habr.com/ru/post/895676/


All Articles