Removing duplicate values from a PowerShell array
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:
Apples
Banana
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
$a | sort -unique
This works with case-insensitive, therefore removing duplicates strings with differing cases. Solved my problem.
$ServerList = @(
"FS3",
"HQ2",
"hq2"
) | sort -Unique
$ServerList
The above outputs:
FS3
HQ2
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