I have an array of Objects that have 6 properties. That look like this:
$csvData
CURRENT DATE AND TIME : 07/10/2015 08:17:17 CST
USER NAME : userName
COMPUTER NAME : computerName
IP ADDRESS : 192.168.1.1
LOGON SERVER : logonServer
LOGON/OFF : logon
I want to create an array of objects where username and computer name are not duplicated. How can I get only the unique username/computername combo in powershell? Ultimately I would like to remove all duplicates and add a property 'Count' that keeps track of how many duplicates there are.
I have tried:
$csvDataUnique = $csvData | Select-Object 'User Name','Computer Name' -Unique
$csvDataUnique = $csvData | sort -Property 'User Name' | Get-Unique
Selects objects or object properties. 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.
Well, that is about all there is to selecting unique objects from a list. There are three ways to do this: use the Get-Unique cmdlet, use the Unique parameter from the Sort-Object cmdlet, or use the Unique parameter from the Select-Object cmdlet. I invite you to follow me on Twitter and Facebook.
The Unique switched parameter can also be used to find distinct objects by a property in a custom object array. As already explained, the Unique parameter with Select-Object cmdlet finds unique values with case-sensitive string comparison.
An alternative option is to use Get-Unique . It was quite helpful in my situation when I wanted to select objects based on a unique property without some extensive foreach-loop. The object needs to be sorted because Get-Unique compares the strings adjacent to each other. Additionally, the comparison is case-sensitive.
Very similar to Mathias' answer, but will have all of the columns in the output:
$csvDataUnique = $csvData |
Group-Object 'User Name','Computer Name' |
%{ $_.Group | Select 'User Name','Computer Name' -First 1} |
Sort 'User Name','Computer Name'
You can create a custom property with your Select-Object
. So you were pretty close already. Try this:
Select-Object @{Label = "Index"; Expression = {"$($_.'User Name') $($_.'Computer Name')"} } -Unique
It basically combines the two fields into a single string and sorts unique on that. I called the field "Index" but it could be called anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With