LightningWar
LightningWar

Reputation: 975

Where-Object filtering - Alternative to multiple and

Using PowerCLI to filter a list of virtual machines:

Get-VM | Where-Object {$_.Name -ne 'VM1001' -and $_.Name -ne 'VM2002' -and $_.Name -ne 'VM3003' -and $_.Name -ne 'VM4004'} | Select_Object ...

Is there a cleaner/better way to filter results? This would improve script readability.

Thanks

Upvotes: 1

Views: 1198

Answers (1)

Avshalom
Avshalom

Reputation: 8889

Like @JosefZ commented, using the -notin is good for PowerShell version 3 and later:

Get-VM | Where-Object { $_.Name -notin @('VM1001','VM2002','VM3003','VM4004') }

On PowerShell version 2, you can still can use the -notcontains comparison operator:

$Excluded = @('VM1001','VM2002','VM3003','VM4004')
Get-VM | Where-Object { $Excluded -notcontains $_.Name }

Upvotes: 2

Related Questions