Jack Pettersson
Jack Pettersson

Reputation: 1666

Filtering output using "Where-Object" in Powershell

I'm trying to get into PowerShell and have encountered my first hurdle.

when I run

Get-Command | Where-Object CommandType -contains Cmdlet

My output gets filtered so that only commands with "CommandType" property value containing "Cmdlet" gets shown, like so:

enter image description here

Same thing can be done with the object "Source":

Get-Command | Where-Object Source -contains appx

Which gets me:

enter image description here

But when i try to run:

Get-Command | Where-Object Name -contains Add

I get nothing. Why can I filter the output by the objects "CommandType", and "Source but not "Name"? I'm surely missing something here...

Edit: i know i can run:

Get-Command -verb "get"

And get the desired output. But i'm trying to figure out why my "where-object" statement did not work.

Edit 2:

Appearantly if I use the "-match" comparison operator it works...

get-command | where-object Name -match "add"

But isn't "name" properties just strings? -match should be used for Regular expression comparison afaik? I'm so confused right now...

Upvotes: 26

Views: 115040

Answers (1)

Kiran Reddy
Kiran Reddy

Reputation: 2904

use either the like or the match operator:

Get-Command | Where-Object Name -like Add*

this will match add anywhere in the word

Get-Command | Where-Object Name -match Add

but a better way to do this would be:

Get-Command -verb Add

read more about the contains operator here

-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value. Always returns a Boolean value. Returns TRUE only when the test value exactly matches at least one of the reference values.

      PS C:\> "abc", "def" -Contains "def"
      True

Upvotes: 34

Related Questions