Filtering OBJECTS in Powershell

Hey there, When we think of filtering an Object basically that’s just a fancy way to say I am going to look for an answer about a certain Object.

Let’s just say You want to know how to look for the disable accounts in the system?

The answer would be as follows:

Get-LocalUser | Where-Object {$PSItem.Enabled -eq '$False'} 

What is happening right now? Basically we tell powershell show me all the local users using the cmdlet Get-LocalUsers then pipe that result and use the Where-Object because everything on powershell shell is an Object, Commonly this is how you will filter stuff, use curly braces and inside use the variable $PSItem or the underscore like the example below.

Get-LocalUser | Where-Object {$_.Enabled -eq '$false'}

After the underscore, you want to use the property that you want to filter. in this case the property we are working with with is .Enabled

If you want to know what are the properties of an Object just use the Get-Member CmdLet for that Object .

We then go to check if that value for that property is equal to with the -eq to False. Booleans in Powershell true or false are used with the $dollar sign in the front.

You can try different ways and I found out that without the dollar sign it might work too.

Lets just say that we want to find all services that start automatically. The Syntax would look like below:

Get-Service | Where-Object {$_.StartType -EQ 'Automatic'}

or you can use the -Filter Script parameter before the curly braces, either way you get the same result.

Get-Service | Where-Object -FilterScript {$_.StartType -EQ 'Automatic'}

There are different ways to filter Objects. Here is a whole list:

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/where-object?view=powershell-7.3

I will leave up to you to research how to use the Different Ways to filter Objects.

here is a good cheatsheet:

https://hackr.io/blog/powershell-cheat-sheet

The most common that you will see the most are:

-eq / -ceq – value equal to specified value.
-ne / -cne – value not equal to specified value.
-gt / -cgt – value greater than specified value.
-ge / -cge – value greater than or equal to specified value.
-lt / -clt – value less than specified value.
-le / -cle – value less than or equal to specified value.

This is all for now!

PEACE!!

Sources:

https://adamtheautomator.com/powershell-where-object/
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/where-object?view=powershell-7.3
https://petri.com/powershell-where-object/
https://gist.github.com/pcgeek86/336e08d1a09e3dd1a8f0a30a9fe61c8a
https://hackr.io/blog/powershell-cheat-sheet