PowerShell: How to Split Based on New Lines


You can use the following syntax in PowerShell to split based on new lines:

$my_string.Split([Environment]::NewLine)

This particular example will split the string stored in the variable named $my_string based on where new lines occur.

The output from using Split() will contain empty elements between each line.

If you’d like to remove these empty elements then you can use the following syntax:

$my_string.Split([Environment]::NewLine, [System.StringSplitOptions]::RemoveEmptyEntries)

The following example shows how to use each of these methods in practice.

Example: How to Split Based on New Lines in PowerShell

Suppose we create the following string variable named $my_string that contains the names of various basketball teams separated by new lines:

$my_string = "Mavericks`r`nRockets`r`nSpurs`r`nKings"

The following screenshot shows how to use this syntax in practice:

We can use the following syntax to split the team names in this string based on where new lines occur in the string:

$my_string.Split([Environment]::NewLine)

The following screenshot shows how to use this syntax in practice:

Notice that the output contains each team name on its own line, separated by empty lines.

If we would like to split based on new lines and remove these empty lines from the output, we can use the following syntax instead:

$my_string.Split([Environment]::NewLine, [System.StringSplitOptions]::RemoveEmptyEntries)

The following screenshot shows how to use this syntax in practice:

PowerShell split based on new line

Notice that the output contains each team name on its own line and there are no empty lines in the output.

Feel free to use whichever method you prefer.

Note: You can find the complete documentation for the Split operator in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Split String Based on Regex Pattern
PowerShell: How to Split String Based on Tab Characters
PowerShell: How to Split a String Using Multiple Delimiters
PowerShell: How to Split String into Separate Variables

Leave a Reply