PowerShell: How to Filter for Unique Objects


You can use the following syntax in PowerShell to filter for unique objects:

 $team_data | Select * -unique

This particular example will return only the unique rows from the object named $team_data.

By using the -unique operator, we specify that we only want the unique rows.

If you’d like, you can also return unique rows from an object across specific properties:

$team_data | Select Team, Position -unique

This particular example will return the rows that have unique values across the Team and Position properties of the object named $team_data.

The following example shows how to use both of these methods in practice.

Example: How to Filter for Unique Objects in PowerShell

Suppose that we create the following object in PowerShell named $team_data that contains information about various basketball players:

$team_data = "Team, Position, Points
Mavs, Guard, 22
Mavs, Guard, 15
Mavs, Forward, 13
Mavs, Forward, 13
Mavs, Center, 19
Spurs, Guard, 10
Spurs, Guard, 10
Spurs, Forward, 14
Spurs, Forward, 29
Spurs, Forward, 34
" | ConvertFrom-Csv

The following screenshot shows how to use this syntax in practice:

Suppose that we would like to filter the object to only display the unique rows.

We can use the following syntax to do so:

 $team_data | Select * -unique

The following screenshot shows how to use this syntax in practice:

PowerShell filter for unique objects

Notice that only unique rows are returned from the object.

The original object contained 10 rows while this syntax returned only 8 rows, which indicates that there were 2 duplicate rows in the original object.

Also note that we could use the following syntax to return unique rows from an object across specific properties:

$team_data | Select Team, Position -unique

The following screenshot shows how to use this syntax in practice:

PowerShell filter for unique objects across specific properties

This particular example returns the rows that have unique values across the Team and Position properties of the object named $team_data.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Find Duplicate Values in Array
PowerShell: How to Use Where-Object in List
PowerShell: How to Use Where-Object with Multiple Conditions

Leave a Reply