0

How can I remove duplicate values within an array element in PowerShell?

For example:

$array[0] = C1 C1 C3 C3
$array[1] = C1 C1 C2 C2

How can I removed the duplicates in Powershell, so that I have:

$array[0] = C1 C3
$array[1] = C1 C2

I tried $array[0] | Select -Unique but it was not successful. Nothing changed. With $array | Select - Unique the duplicates are removed without considering the single array elements.

Anyone a good idea?

Machavity
  • 30,841
  • 27
  • 92
  • 100
TheCodingKing
  • 97
  • 2
  • 10

1 Answers1

2

This works perfect if you use spaces as delimiter however if your string should have had a space then it will be removed. Ideally, you could create your $array with a specific delimiter like | or ; or , that's up to you.

$array=@(
    'C1 C1 C3 C3'
    'C1 C1 C2 C2'
    'C1 C2 C3 C4'
    'C1 C1 C2 C2'
    'C1 C2 C3 C3'
    'C1 C2 C2 C2'
)

for($i=0;$i -lt $array.Count;$i++)
{
    $array[$i] = ($array[$i] -split '\s+' | Select-Object -Unique) -join ' '
}

PS /> $array
C1 C3
C1 C2
C1 C2 C3 C4
C1 C2
C1 C2 C3
C1 C2
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • 1
    Thank yo, +1 from me, I was adding/removing LogonWorkstations in AD, the following splits them by comma, removes duplicates, and re-joins. `$LogonWorkstations = ($LogonWorkstations -split ',' | Select-Object -Unique) -join ','` – Aubs Jul 19 '23 at 14:19