Remove Duplicate entry from a variable

Viewed 101

I have a mail variable with content like this

if ($user -eq 'abc') {$mail += 'abc@ae.com;'}
elseif ($user -eq 'efg') {$mail += 'efg@ae.com;'}
elseif ($user -eq 'hij') {$mail += 'hij@ae.com;'}
elseif ($user -eq 'klm') {$mail += 'klm@ae.com;'}

Now the $mail variable will have content like this abc@ae.com;klm@ae.com;abc@ae.com;hij@ae.com;klm@ae.com

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

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

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:

('abc@ae.com;klm@ae.com;abc@ae.com;hij@ae.com;klm@ae.com' -split ';' | Select-Object -Unique) -join ';'

Output:

abc@ae.com;klm@ae.com;hij@ae.com

Split + Select-Object -Unique do the job

("abc@ae.com;klm@ae.com;abc@ae.com;hij@ae.com;klm@ae.com".Split(';') |Select-Object -Unique) -join ";"

you could use directly linq:

$arr = "abc@ae.com;klm@ae.com;abc@ae.com;hij@ae.com;klm@ae.com".Split(";")
[Linq.Enumerable]::Distinct($arr) -join ";"
Related