In PowerShell, we can use the split operator (-Split) to split a string text into an array of strings or substrings. The split operator uses whitespace as the default delimiter, but you can specify other characters, strings, and patterns as the delimiter. We can also use a regular expression (regex) in the delimiter.
Split string by space separator and convert into array of words
$String = "This is simple string"
$ArrayOfString = $String -split " "
#Output
This
is
simple
string
Separate string by comma
$String = "a,b,c,d "
$String -split ","
Preserve delimiter or separator
By default, the delimiter is omitted from the result array. To preserve all or part of the delimiter, enclose in parentheses the part that you want to preserve.
$String = "FirstName_and_LastName_and_Address"
$String -split "_and_" #Do no preserve the separator.
$String = "FirstName_and_LastName_and_Address"
$String -split "(_and_)" #Preserve all part of the delimiter
$String = "FirstName_and_LastName_and_Address"
$String -split "_(and)_" #Preserve some part of the delimiter
Split String using Regular Expression (Regex)
The following command splits the string which is in Distinguished Name format and returns only the name components.
$String = "OU=MTS,OU=CORP,DC=CONTOSO,DC=COM"
($String -split ',*..=' ) -ne ''
Advertisement