How can I split a string into an array on every newline?

Viewed 12177

In my situation, I will have a string that looks like this.

$emailList = "example@mail.com
              example2@mail.com
              example3@mail.com"

How can I port this into an array with no white-space so it would look like

$emailList = @("example@mail.com","example2@mail.com","example3@mail.com"
3 Answers
$emailList = "example@mail.com
              example2@mail.com
              example3@mail.com"
$emailList.Split([Environment]::NewLine,[Stringsplitoptions]::RemoveEmptyEntries).trim()

-split on the left side splits on variable whitespace:

$emailList = -split 'example@mail.com
              example2@mail.com
              example3@mail.com'
$emailList

example@mail.com
example2@mail.com
example3@mail.com

You can also form an array list this. @() is almost never needed.

$emailList = 'example@mail.com','example2@mail.com','example3@mail.com'

Or as a shortcut (echo is an alias for write-output):

$emailList = echo example@mail.com example2@mail.com example3@mail.com
Related