How to use Powershell Where-Object like an IN statement
24,618
Solution 1
Use the -contains
operator. Like:
$dbs = "testDB", "master", "model", "msdb"
foreach ($db in ($svr.Databases | where-object {$dbs -contains $_.name } )) {
write-output $db.name
}
Use help about_Comparison_Operators
to learn more about this and other comparison operators.
Update:
PowerShell v3 has added the -in
operator. The example in the original question will work in v3.
Solution 2
You can use a regex:
$svr.Databases | where { $_.name -match 'testDB|master|model|msdb' } | foreach { $db.name }
Solution 3
Powershell has an -in
operator since Powershell 3
$srv.Databases | where Name -in "master","model","msdb" | write-output { $_.Name }
Further Reading: Docs on Comparison Operators > Containment Operators
Author by
8kb
Updated on July 09, 2022Comments
-
8kb almost 2 years
I have the following code which works:
foreach ($db in $svr.Databases | where-object { $_.name -eq "testDB" -or $_.name -eq "master" -or $_.name -eq "model" -or $_.name -eq "msdb" } ) { write-output $db.name }
Is a cleaner way to do this?
Something like:
foreach ($db in $svr.Databases | where-object {$_.name -in "testDB, master, model, msdb" } ) { write-output $db.name }
-
Christine about 8 yearsAren't you missing a paren there?
-
Rynant about 8 yearsYes, I did miss a paren. Thanks, fixed.
-
Martin Smith over 6 yearsThe example in the original question won't quite work - as it is a comma delimited string - not an array.