[powershell] PowerShell and the -contains operator

Consider the following snippet:

"12-18" -Contains "-"

You’d think this evaluates to true, but it doesn't. This will evaluate to false instead. I’m not sure why this happens, but it does.

To avoid this, you can use this instead:

"12-18".Contains("-")

Now the expression will evaluate to true.

Why does the first code snippet behave like that? is there something special about - that doesn't play nicely with -Contains? The documentation doesn't mention anything about it.

This question is related to powershell operators string-matching

The answer is


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

Reference: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6


You can use like:

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

Or split for contains:

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

-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.


Examples related to powershell

Why powershell does not run Angular commands? How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line? How to print environment variables to the console in PowerShell? Check if a string is not NULL or EMPTY The term 'ng' is not recognized as the name of a cmdlet VSCode Change Default Terminal 'Connect-MsolService' is not recognized as the name of a cmdlet Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet Change directory in PowerShell

Examples related to operators

What is the difference between i = i + 1 and i += 1 in a 'for' loop? Using OR operator in a jquery if statement What is <=> (the 'Spaceship' Operator) in PHP 7? What does question mark and dot operator ?. mean in C# 6.0? Boolean operators ( &&, -a, ||, -o ) in Bash PowerShell and the -contains operator How do I print the percent sign(%) in c Using the && operator in an if statement What do these operators mean (** , ^ , %, //)? How to check if div element is empty

Examples related to string-matching

Filter multiple values on a string column in dplyr PowerShell and the -contains operator Check if string matches pattern How to check if matching text is found in a string in Lua? Check whether a string contains a substring Perl - If string contains text? How to search a specific value in all tables (PostgreSQL)? javascript regular expression to check for IP addresses Regular Expression Match to test for a valid year How do I check if a string contains a specific word?