Reputation: 81
Can anyone please help me to remove extra commas from string and pass them to another string in well formatted to send an email from PowerShell.
$emails = "[email protected],,,[email protected],[email protected],,"
I'm expecting string like below
$emailsTo = "[email protected],[email protected],[email protected]"
Upvotes: 1
Views: 2380
Reputation: 440471
To complement the existing, helpful answers:
A more efficient and concise reformulation of Esperento57's answer:
> ',,[email protected],,,[email protected],[email protected],,' -split ',' -ne '' -join ','
[email protected],[email protected],[email protected]
An alternative approach using the .NET Framework directly, via the [string]
type's .Split()
method with the RemoveEmptyEntries
option:
> $emails = ',,[email protected],,,[email protected],[email protected],,'
> $emails.Split(',', [StringSplitOptions]::RemoveEmptyEntries) -join ','
[email protected],[email protected],[email protected]
Upvotes: 1
Reputation: 200523
Use the -replace
operator to collapse consecutive commas to a single one and remove leading/trailing commas from beginning and end of the string:
$emails = '[email protected],,,[email protected],[email protected],,'
$emailsTo = $emails -replace ',+', ',' -replace '^,|,$'
Upvotes: 3
Reputation: 17492
try this
$emails = ("[email protected],,,[email protected],[email protected],," -split "," | where{$_ -ne ""}) -join ","
Upvotes: 1