Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering output using "Where-Object" in Powershell

Tags:

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...

like image 907
Jack Pettersson Avatar asked Feb 11 '16 08:02

Jack Pettersson


People also ask

How do I filter an object in PowerShell?

There are many ways you can filter objects and their data in PowerShell. For example, you can use the Where-Object, Select-Object, Select-String, ForEach-Object, and Out-GridView cmdlets either separately or in conjunction with each other.

What is where object in PowerShell?

The Where-Object cmdlet selects objects that have particular property values from the collection of objects that are passed to it. For example, you can use the Where-Object cmdlet to select files that were created after a certain date, events with a particular ID, or computers that use a particular version of Windows.

How do I select output in PowerShell?

The Select-Object cmdlet selects specified properties of an object or set of objects. It can also select unique objects, a specified number of objects, or objects in a specified position in an array. To select objects from a collection, use the First, Last, Unique, Skip, and Index parameters.


1 Answers

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
like image 171
Kiran Avatar answered Sep 30 '22 13:09

Kiran