Skip navigation
blue_network.jpg Getty Images

PowerShell -contains -like

Don't get confused: -Contains and -Like are drastically different. Here's what they do.

For more technical explainers on PowerShell, read our updated 2021 report: PowerShell 101: A Technical Explainer for IT Pros.

When folks are exploring the operators available in PowerShell, they'll often run across two seemingly similar, but drastically different, operators -- and get confused by them.

I'll often see someone try this:

if ($string -contains '*win*') { }

They're trying to see if $string contains the letters "win," but, unfortunately, that's not what -contains does. What they really want to use is the -like operator:

if ($string -like '*win*') { }

I know it doesn't read as nicely when you say it out loud. But -like is the correct operator for this task.

The -contains operator is a bit trickier. It's designed to tell you if a collection of objects includes ('contains') a particular object. Now, if your collection of object is a bunch of strings, this is pretty straightforward.

$coll = "one','two','three','four'
if ($coll -contains 'one') { }

It gets harder when the collection contains complex objects. This won't work like you might think:

$coll = Get-Service
if ($coll -contains 'BITS') { }

The variable $coll does not contain the string "BITS." What it contains is a service object whose Name property is BITS. You can't really use -contains in this fashion, because it compares the entire object.

For example:

# Get all processes
$procs = Get-Process

# Get just one process
$proc = Get-Process | Select -first 1

# Check it
$procs -contains $proc

This will almost always be False. That's because in the time it takes to run the second command, the first process has changed. Its memory, CPU, or some other value has changed. Although $procs does contain the same actual process as $proc, not every single property is exactly the same in both instances. So -contains can't detect the match.

Learn more about the "Top Ten PowerShell Annoyances."

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.