How can I remove duplicates from a PowerShell array?

0
21
Asked By CuriousCoder92 On

Hey there! I'm working with PowerShell and I need to extract unique items from an array. I'm using `Invoke-RestMethod` to fetch a list of servers, and the response is in JSON format. The problem is that some servers show up in multiple groups, which creates duplicates. For instance, the server with the alias `server_2` appears in two different groups. When I try to use `Sort-Object -Unique` or `Get-Unique`, I'm only getting one server back instead of the others. I also discovered that `Get-Unique` only works on sorted input, which I wasn't aware of at first. Can anyone help me figure out how to get unique items in my array while still keeping all the properties of each server?

1 Answer

Answered By TechGuruu99 On

You can use the `-Property` parameter with `Sort-Object` to specify which property you want to be unique. Just run this command: `$response.groups.servers | Sort-Object -Property name -Unique`. This will help you filter the duplicates based on the 'name' field.

CuriousCoder92 -

I had a feeling I was missing something obvious. Thank you very much!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.