PoshBytes: Is it Contained or In an Array?
Should you use -contains or -in in your PowerShell comparison? This PoshBytes solves the common membership test confusion by showing when something is contained versus in.
This post is a companion for the video embedded below. Scroll down to see the code from the video.
The Setup
$awesome = 'IT','DevOps','SecOps'
$awesome -contains 'IT'
'IT' -contains $awesome
$awesome -in 'IT'
'IT' -in $awesome
$users
When Something Is “Contained”
-Contains Collection first
$users |
Where-Object { $awesome -contains $_.Department }
When Something Is “In”
-In Value first
$users |
Where-Object { $_.Department -in $awesome }
Use in logic operations
Ordering remains the same in logic operations
$users | ForEach-Object {
if ($awesome -contains $_.Department) {
Write-Host "Awesome: $($_.Name)" -F Green
}
else{
Write-Host "Not Awesome: $($_.Name)" -F Red
}
}
Not Contains and In
Not order stays the same but return logic is reversed
$users | ForEach-Object {
if ($_.Department -notin $awesome) {
Write-Host "Sorry: $($_.Name) :("
}
}
Wrap Up
• -contains requires the collection on the left
• -in requires the value on the left
• Both perform membership comparisons
• Match the operator to your sentence structure