Occasionally, you need to process multi-line text line by line. Here is an example of a multi-line string to start with:

# working with 1-dimensional input

# $data is a single string
$data = @'


An efficient way to split the text into individual lines is using the -split operator with a regular expression that can deal with the variety of platform-dependent line terminators:

# split the string in individual lines
# $array is an array with individual lines now

$regex = '[\r\n]{1,}'
$array = $data -split $regex 



Here are a few alternatives for the regular expression found in $regex that you encounter in scripts:

Regular expression for splitting Remarks
/r Resembles “Carriage Return” (ASCII 13). If the OS does not use this for new lines, split fails. If OS uses this plus “Line Feed” (ASCII 10), remaining invisible line feed characters damage the strings.
/n Same as above, just the opposite
[\r\n]+ Same as in the example code above. PowerShell splits at both characters provided there are one or more. This way, CR, LF, or CRLF, LFCR, are all removed while splitting. However, multiple consecutive new lines will all be removed, too: CRCRCR or CRLFCRLF
(\r\n|\r|\n) This will correctly split a single line break, regardless of which characters a particular OS uses. It leaves consecutive blank lines intact.

If you read text from a text file, Get-Content automatically splits the text into lines. To read the entire text content as a single string, you’d need to add the -Raw parameter.

Twitter This Tip! ReTweet this Tip!