Home > Back-end >  Why does the -Match Operator sometimes return the matching strings and other times booleans?
Why does the -Match Operator sometimes return the matching strings and other times booleans?

Time:12-20

This is my favourite operator in Powershell, but sometimes I feel like it despises me !!

Lets say I have a string like so in $Clipboard:

PowerShell Documentation - PowerShell | Microsoft Learn
https://learn.microsoft.com/en-us/powershell/

Welcome to Python.org
https://www.python.org/

GitHub
https://github.com/

Invoking:

$Clipboard.trim()  -split '\n' -NotMatch "^$"

Returns the actual strings that got matched, not booleans:

PowerShell Documentation - PowerShell | Microsoft Learn
https://learn.microsoft.com/en-us/powershell/
Welcome to Python.org
https://www.python.org/
GitHub
https://github.com/

Yet if I do something like this:

$Clipboard.trim()  -split '\n' -NotMatch "^$"| % {$Title = $_ -Match "https?:|//www\." 
$Title
} 

I get booleans:

False
True
False
True
False
True

I am starting to avoid -Match now, send help please.

CodePudding user response:

This is by design. In your first example, where you get the strings back, you are passing a collection to -match and it is performing an implicit enumeration and returning the matched strings. in you second example, you are enumerating the collection yourself and testing each item individually, hence the Boolean instead.

This behaviour is explicitly stated in the -match operator help:

When the input of these operators is a scalar value, they return a Boolean value. When the input is a collection of values, the operators return any matching members. If there are no matches in a collection, the operators return an empty array.

CodePudding user response:

This is a general feature of PowerShell's comparison operators:

  • With a scalar (single) LHS operand, they return a [bool] result ($true or $false).

  • With an array (collection) LHS operand, they act as filters and return those LHS elements that match, as an array.

With respect to the -match operator, specifically, note that the automatic $Matches variable is only populated with a scalar LHS.

  • Related