Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]" 
like image 357
pencilCake Avatar asked Jun 10 '13 16:06

pencilCake


People also ask

How do you split a string into an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split data in PowerShell?

Use one of the following patterns to split more than one string: Use the binary split operator (<string[]> -split <delimiter>) Enclose all the strings in parentheses. Store the strings in a variable then submit the variable to the split operator.

How do you slice a string in PowerShell?

When you want to extract a part of a string in PowerShell we can use the Substring() method. This method allows us to specify the start and length of the substring that we want to extract from a string.

How do you split a string into two variables in PowerShell?

Use the Split() Function to Split a String Into Separate Variables in PowerShell. The Split() is a built-in function used to split a string in PowerShell. We can store the result of the Split() function into multiple variables.


2 Answers

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.

like image 182
Mike Zboray Avatar answered Sep 22 '22 06:09

Mike Zboray


[string[]]$recipients = $address.Split('; ',[System.StringSplitOptions]::RemoveEmptyEntries) 
like image 24
Shay Levy Avatar answered Sep 22 '22 06:09

Shay Levy