Home > Software engineering >  Simplest PowerShell syntax for using Where-Object on a list of strings
Simplest PowerShell syntax for using Where-Object on a list of strings

Time:11-12

If I have a list of people with a "Name" property that's a string I can filter with

$People | ? Name -Match "Smith"

But there doesn't seem to be a similarly way to filter a plan list of strings. I have to write a more complex syntax like

Names | ? {$_ -Match "Smith"}

Is there a simpler syntax? It's something I have to do regularly, and I always wonder if there's something I'm missing.

Note: I've simplified a bit far here - I want it to work when it's consuming the output from a function, not just an array.

CodePudding user response:

I assume that in Names | ? {$_ -Match "Smith"} the Names is a variable that is an array of strings?

If so, you could use just Names -Match "Smith", like this:

$Names = @("Norman McCray", "Kristin Pittman", "Patrick Smith", "John Smith");

$Names -Match "Smith";

And the output will be "Patrick Smith", "John Smith", as expected.

Update to the comment

Names is a function

If Names is a function you can force the result to be an array and the syntax above is still valid. Example:

function Names { 
  return "Norman McCray", "Kristin Pittman", "Patrick Smith", "John Smith";
}

# Will return all results
Names -Match "Smith";

# Will return filtered values: "Patrick Smith", "John Smith"
@(Names) -Match "Smith";

Docs

As zett42 sugested in the comment, here's reference:

The matching operators (-like, -notlike, -match, and -notmatch) find elements that match or do not match a specified pattern.

And

When the input of these operators is a scalar value, they return a Boolean value. When the input is a collection of values, the operators return any matching members. If there are no matches in a collection, the operators return an empty array.

Source

CodePudding user response:

A lot of operators work with arrays on the left side.

'joe','john','james' -match 'jo'

joe
john

Or select-string, although that returns an matchinfo object. It will convert to string in certain contexts.

echo joe john james | select-string jo

joe
john


echo joe john james | select-string jo | % gettype

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    MatchInfo                                System.Object
True     False    MatchInfo                                System.Object

  • Related