Removing duplicate values from a PowerShell array
Use Select-Object
(whose alias is select
) with the -Unique
switch; e.g.:
$a = @(1,2,3,4,5,5,6,7,8,9,0,0)$a = $a | select -Unique
Another option is to use Sort-Object
(whose alias is sort
, but only on Windows) with the -Unique
switch, which combines sorting with removal of duplicates:
$a | sort -unique
In case you want to be fully bomb proofed, this is what I would advise:
@('Apples', 'Apples ', 'APPLES', 'Banana') | Sort-Object -Property @{Expression={$_.Trim()}} -Unique
Output:
ApplesBanana
This uses the Property
parameter to first Trim()
the strings, so extra spaces are removed and then selects only the -Unique
values.
More info on Sort-Object
:
Get-Help Sort-Object -ShowWindow