Enigma
Enigma

Reputation: 123

Remove Duplicate entry from a variable

I have a mail variable with content like this

if ($user -eq 'abc') {$mail += '[email protected];'}
elseif ($user -eq 'efg') {$mail += '[email protected];'}
elseif ($user -eq 'hij') {$mail += '[email protected];'}
elseif ($user -eq 'klm') {$mail += '[email protected];'}

Now the $mail variable will have content like this [email protected];[email protected];[email protected];[email protected];[email protected]

How do i remove the duplicate mail from $mail variable. tried the below but no luck.

$mail = $mail | select -unique
$mail | sort | Get-Unique

Upvotes: 1

Views: 513

Answers (2)

Frenchy
Frenchy

Reputation: 17007

Split + Select-Object -Unique do the job

("[email protected];[email protected];[email protected];[email protected];[email protected]".Split(';') |Select-Object -Unique) -join ";"

you could use directly linq:

$arr = "[email protected];[email protected];[email protected];[email protected];[email protected]".Split(";")
[Linq.Enumerable]::Distinct($arr) -join ";"

Upvotes: 1

Martin Brandl
Martin Brandl

Reputation: 58931

I would use the -split operator to get an array of mails, then use the Select-Object -unique cmdlet to remove the duplicates and finally join the array back to the desired string:

('[email protected];[email protected];[email protected];[email protected];[email protected]' -split ';' | Select-Object -Unique) -join ';'

Output:

[email protected];[email protected];[email protected]

Upvotes: 2

Related Questions