Beware the Powershell -Contains operator

Many of us tend to jump quickly, into a new programming or scripting language, applying knowledge we’ve learned elsewhere to the current task at hand. Broadly speaking this works well but these always a little gotcha to trip you up!

A good example is the Powershell -contains operator. It’s not like .Net String.Contains method as you might first think.

?View Code POWERSHELL
$var = "Rhys Campbell";
$var -contains "Rhys";

The result of this is false. Why? Because the -contains operator in Powershell is used for testing for items in an array.

?View Code POWERSHELL
$var = "Rhys Campbell", "Joe Bloggs";
$var -contains "Rhys Campbell";

Will return true, but;

?View Code POWERSHELL
$var -contains "Rhys*";

Will return false as wildcards will not work as we assume they will. For wildcard matching we can use the -match operator.

?View Code POWERSHELL
$var = "Rhys Campbell";
$var -match "Rhys";

This will return true when matching simple strings or the matching items from an array of strings. Now I’m going to try and remember what assumption is the mother of (NSFW, contains cussing).


3 Comments

  1. Goran says:

    You’re a lifesaver! I’ve spent a few hours thinking of what went wrong with my code and way of thinking :\
    Thanks!

  2. Rhys says:

    Hi Goran,

    Yes, it’s easily done!

    Cheers,

    Rhys

  3. Raghav says:

    Thanks for the help.

Leave a Reply