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?

10
  • 3
    You should comma separate array elements when creating your array. Commented May 4, 2021 at 16:20
  • How is this array created? Are C1 C1 C3 C3 different property values or is it a string? Commented May 4, 2021 at 16:22
  • @SantiagoSquarzon It is a String. It gets these values from an excel file Commented May 4, 2021 at 16:23
  • @AdminOfThings Also if I comma seperate it, how can I remove duplicates in one array element? Commented May 4, 2021 at 16:25
  • 4
    If they are space separated elements in a string, then you can use $array[0] -split ' ' | select -unique. Commented May 4, 2021 at 16:26

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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 ','

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.