New Operator -In

by Mar 1, 2013

In PowerShell v3, you can use a new simplified syntax for Where-Object. Both lines below list all files in your Windows folder that are larger than 1MB:

# old syntax:
PS> Dir $env:windir | Where-Object { $_.Length -gt 1MB }
# new alternate simplified syntax:
PS> Dir $env:windir | Where-Object Length -gt 1MB 

The simplified syntax can produce strange results, too. Here is a more complex example. It uses a whitelist to list only certain services:

PS> $WhiteList = @('Spooler','WinRM','WinDefend')
PS> Get-Service | Where-Object { $WhiteList -contains $_.Name } 

This is just an example, and we know you could have simplified it like this, too:

Get-Service -Name $WhiteList

But how would you simplify it using the new Where-Object syntax, though? This would be the natural way:

Get-Service | Where-Object $WhiteList -contains Name 

It fails, though.

As it turns out, when you do use the simplified syntax, the property you are referring to always must come first. So you cannot use operators like -contains and -notcontains. That's why Microsoft has added the two new operators -in and -notin. They work exactly like -contains and -notcontains, just with reversed arguments:

Get-Service | Where-Object Name -In $WhiteList  

Twitter This Tip! ReTweet this Tip!