35

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

$address = "foo@bar.com; boo@bar.com; zoo@bar.com"

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

[string[]]$recipients = "foo@bar.com", "boo@bar.com", "zoo@bar.com"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pencilCake
  • 51,323
  • 85
  • 226
  • 363
  • 1
    Possible duplicate of [Split string with PowerShell and do something with each token](http://stackoverflow.com/questions/11348506/split-string-with-powershell-and-do-something-with-each-token) – Michael Freidgeim Jan 14 '17 at 12:24

3 Answers3

60

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
12
[string[]]$recipients = $address.Split('; ',[System.StringSplitOptions]::RemoveEmptyEntries)
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
10

Remove the spaces from the original string and split on semicolon

$address = "foo@bar.com; boo@bar.com; zoo@bar.com"
$addresses = $address.replace(' ','').split(';')

Or all in one line:

$addresses = "foo@bar.com; boo@bar.com; zoo@bar.com".replace(' ','').split(';')

$addresses becomes:

@('foo@bar.com','boo@bar.com','zoo@bar.com')
DarkAjax
  • 15,955
  • 11
  • 53
  • 65