Iterating through a variable line by line

ForEach ($line in $($result -split "`r`n"))
{
    Write-host $Line
}

By your description, your variable is a string with newlines. You can turn it into an array of single-line string by calling this:

$result = $result -split "`r`n"

Here's a solution based on RegexMatch, which is the default behavior of split.
This will work with all types of line endings:

  • Windows (CR LF) \r\n
  • old Macintosh (CR) \r
  • Unix (LF) \n
($result -split "\r?\n|\r") | Out-Host

If you want to get rid of consecutive line breaks you can use:

($result -split "[\r\n]+") | Out-Host

Tags:

Powershell