PowerShell -contains -like

When folks are exploring the operators available in PowerShell (help about_comparison_operators), they'll often run across two similar-seeming, 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. Sounds kinda Valley Girl, I suppose. "If, like, this variable, like, is like, you know, this wildcard, omigod, like really?" 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."

Want to ask a question about this article? I'll answer at http://powershell.com/cs/forums/230.aspx!


Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×