Reputation: 75
In my situation, I will have a string that looks like this.
$emailList = "[email protected]
[email protected]
[email protected]"
How can I port this into an array with no white-space so it would look like
$emailList = @("[email protected]","[email protected]","[email protected]"
Upvotes: 7
Views: 17717
Reputation: 27428
-split on the left side splits on variable whitespace:
$emailList = -split '[email protected]
[email protected]
[email protected]'
$emailList
[email protected]
[email protected]
[email protected]
You can also form an array list this. @() is almost never needed.
$emailList = '[email protected]','[email protected]','[email protected]'
Or as a shortcut (echo is an alias for write-output):
$emailList = echo [email protected] [email protected] [email protected]
Upvotes: 0
Reputation: 568
$emailList = "[email protected]
[email protected]
[email protected]"
$emailList.Split([Environment]::NewLine,[Stringsplitoptions]::RemoveEmptyEntries).trim()
Upvotes: 1
Reputation: 23355
Per the comments, if you do this:
($emailList -split '\r?\n').Trim()
It uses -split
to separate the list in to an array based on the new line/return charaters and then .Trim()
to remove any whitespace either side of each string.
Following this the result is now already an array. However if you explicitly want the output to be as a list of comma separated strings surrounded by double quotes you could then do this:
(($emailList -split '\r?\n').Trim() | ForEach-Object { '"'+$_+'"' }) -Join ','
Which uses ForEach-Object
to add quote marks around each entry and then uses -Join
to connect them with a ,
.
Upvotes: 14