Question

With the advent of PowerShell V3 instead of having to write:

Get-Process | Where { $_.ProcessName -match "win" }

...one could now write the more terse:

Get-Process | Where ProcessName -match "win"

... a clear win (ahem) for shell use.

Now let's say I had a simple array of strings, call it $stuff. Is it possible to reduce this:

$stuff | Where { $_ -match "win" }

...in an analogous way to the first example, i.e. removing the script block and referring to the entire object, in this case?

Was it helpful?

Solution

To reduce

$stuff | Where { $_ -match "win" } 

you can always do it like this (works for all powershell version):

$stuff = "a","b","win", "winona", "d", "windows"
$stuff -match "win"
win
winona
windows

OTHER TIPS

The form Get-Process | Where ProcessName -match "win" is called comparison statement. It's poorly a documented feature, as Where-Object's documentation doesn't really explain what those are about.

The reason comparison statement works for Get-Process but not for $stuff is that the former returns an array of System.Diagnostics.Process objects whlist the later is String. The comparison statements expects property name for filtering.

Let's look at what's available in each array member. First off processes like so,

$proc = get-process
gm -InputObject $proc[0] -MemberType property
   TypeName: System.Diagnostics.Process

Name                       MemberType     Definition
...
ProcessName                Property       string ProcessName {get;}
...

So, there is a ProcessName property, thus Where-Object can filter with it as seen.

The string array:

$stuff = @("foo", "bar", "zoffo", "qazzer")
gm -InputObject $stuff[0] -MemberType property

   TypeName: System.String

Name   MemberType Definition
Length Property   int Length {get;}

There is only one property in a String which is it's length. Sure enough, it can be used for filtering like so,

$stuff | where length -ne 3
zoffo
qazzer
$stuff | where length -eq 3
foo
bar

As there are no other property typed members, the only way to filter the string array is by the classic script block mode.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top