How can I split a string into an array on each new line?

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 put this in an array without a space so that it looks like

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

      

+3


source to share


1 answer


In the comments, if you do this:

($emailList -split '\r?\n').Trim()

      

It uses -split

to split the list into an array based on new line / back characters, and then .Trim()

to remove any spaces from each side of each line.



After that, the result has already become an array. However, if you explicitly want the result to be a comma-separated list of strings surrounded by double quotes, you could do this:

(($emailList -split '\r?\n').Trim() | ForEach-Object { '"'+$_+'"' }) -Join ','

      

Uses ForEach-Object

to add quotation marks around each entry and then uses -Join

to join with ,

.

+4


source







All Articles