pencilCake
pencilCake

Reputation: 53223

How to split a string content into an array of strings in PowerShell?

I have a string that has email addresses separated by semi-colon:

$address = "[email protected]; [email protected]; [email protected]"

How can I split this into an array of strings that would result as the following?

[string[]]$recipients = "[email protected]", "[email protected]", "[email protected]"

Upvotes: 35

Views: 110632

Answers (3)

Mike Zboray
Mike Zboray

Reputation: 40818

As of PowerShell 2, simple:

$recipients = $addresses -split "; "

Note that the right hand side is actually a case-insensitive regular expression, not a simple match. Use csplit to force case-sensitivity. See about_Split for more details.

Upvotes: 62

user2453734
user2453734

Reputation:

Remove the spaces from the original string and split on semicolon

$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')

Or all in one line:

$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')

$addresses becomes:

@('[email protected]','[email protected]','[email protected]')

Upvotes: 10

Shay Levy
Shay Levy

Reputation: 126712

[string[]]$recipients = $address.Split('; ',[System.StringSplitOptions]::RemoveEmptyEntries)

Upvotes: 12

Related Questions