Powershell string contains

From MyWiki
Revision as of 15:48, 8 December 2014 by George2 (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
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