Powershell match a sub-property

Viewed 21

It's straightforward to find an object in a list that matches a property.

$object1 | Get-Member
name   Property string name
id     Property int id

$listOfObjects | Where-Object name -eq "MyName"
MyName 37

But what if it's a sub-property?

$object1 | Get-Member
name    Property    list

$object1.name | Get-Member
firstName    Property    string     firstName
lastName     Property    string     lastName

$listOfObjects | Where-Object name.firstName -eq "Bob"
No results returned

I found such a case when managing a WSUS server through Powershell. I want to find every update with specific letters in the title. Code is below. Ellipses (...) represent redacted text. Comments (#) re my thought process.

$updates = Get-WsusUpdate

$updates[0]
Title        Classification    Installed...Percentage    Approved
-----        --------------    ----------------------    --------
Microsoft... Updates                                     Unapproved
#Ah, there's the title, in a property named "Title". I can filter based on Title. 
#Let's do Get-Member to get more information about Title. 

$updates[0] | Get-Member
TypeName: Microsoft.UpdateServices.Commands.WsusUpdate
...
Update    Property    Microsoft.UpdateServices.Administration.IUpdate Update {get;}
...
#Hmm, Title is not present in Get-Member. What if I see the members of the Update property

$updates[0].update | Get-Member
TypeName: Microsoft.UpdateServices.Administration.IUpdate
...
Title    Property    string title {get;set}
...
#Ah, there it is. 

$update[0].update.title
Windows Server Update Services 3.0 SP2.....
#Found it! I need to filter on $_.update.title

$update | Where_Object $_.update.title -match "Windows"
LOL No way.

Do you know how I can filter a list based on a sub-property like that?

1 Answers

When you're using a statement such as:

$listOfObjects | Where-Object Name -EQ "MyName"

You're using what's called Comparison statement which supports a filtering such as the one above.

Where-Object <Property Name> <Comparison Operator> <Property Value>

However it does not support nested properties, for that you must use a Script block for your filtering logic:

Get-WsusUpdate | Where-Object { $_.Update.Title -match "Windows" }

For more details on this see the Description section from Where-Object official documentation.

Related