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
}
The Where-Object cmdlet selects objects that have particular property values from the collection of objects that are passed to it. For example, you can use the Where-Object cmdlet to select files that were created after a certain date, events with a particular ID, or computers that use a particular version of Windows.
% is an alias for the ForEach-Object cmdlet. An alias is just another name by which you can reference a cmdlet or function.
'?' is an alias to the Where-Object cmdlet. Where-Object takes a scriptblock (e.g '{...}') and evaluates its code. If the code evaluates to $true, the current object is written to the pipeline and is available to the next command in chain, otherwise ($false) the object is discarded.
' symbol and Where are both aliases for Where-Object. Syntax Where-Object [-filterScript] {scriptblock} [-inputObject psobject] [CommonParameters] Key -FilterScript scriptblock An expression that resolves to a Boolean (TRUE/FALSE) value. This will determine which input objects will be passed along the command pipeline.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With