Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell and the -contains operator

People also ask

What is the and operator in PowerShell?

Long description. The PowerShell logical operators connect expressions and statements, allowing you to use a single expression to test for multiple conditions. For example, the following statement uses the and operator and the or operator to connect three conditional statements.

How do I use && in PowerShell?

A && will run the second command only if the first completes without error. This is different from piping commands together with | in that output from the first command is not sent to the second command, the commands are just simply run one after the other and output for each is sent to its usual place.

What does :: mean in PowerShell?

Static member operator :: To find the static properties and methods of an object, use the Static parameter of the Get-Member cmdlet. The member name may be an expression. PowerShell Copy.

What is @() in PowerShell script?

What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.


The -Contains operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.

From the documentation you linked to:

-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.

In the example you provided you're working with a collection containing just one string item.

If you read the documentation you linked to you'll see an example that demonstrates this behaviour:

Examples:

PS C:\> "abc", "def" -Contains "def"
True

PS C:\> "Windows", "PowerShell" -Contains "Shell"
False  #Not an exact match

I think what you want is the -Match operator:

"12-18" -Match "-"

Which returns True.

Important: As pointed out in the comments and in the linked documentation, it should be noted that the -Match operator uses regular expressions to perform text matching.


-Contains is actually a collection operator. It is true if the collection contains the object. It is not limited to strings.

-match and -imatch are regular expression string matchers, and set automatic variables to use with captures.

-like, -ilike are SQL-like matchers.


You can use like:

"12-18" -like "*-*"

Or split for contains:

"12-18" -split "" -contains "-"

  • like is best, or at least easiest.
  • match is used for regex comparisons.

Reference: About Comparison Operators