Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Powershell Where-Object like an IN statement

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
}
like image 907
8kb Avatar asked Aug 24 '11 16:08

8kb


People also ask

What is where-object in PowerShell?

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.

What does %% mean in PowerShell?

% is an alias for the ForEach-Object cmdlet. An alias is just another name by which you can reference a cmdlet or function.

What is the alias for where-object command?

'?' 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.

Is an alias for where-object command True or false?

' 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.


1 Answers

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.

like image 115
Rynant Avatar answered Oct 12 '22 13:10

Rynant