JustAGuy
JustAGuy

Reputation: 5941

Iterating through a variable line by line

I have a small script that outputs text into a variable. I need to go through it line by one in order to parse it. I could do this by outputting the variable to a text file and then reading it using Get-Content but that seems a bit redundant.

My script connects to a Fortigate unit and runs a certain query. It's response is what I'm looking to parse.

New-SshSession 10.0.0.138 -Port 65432 -Credential (Get-Credential) -AcceptKey
$command = 'config router policy
show'
$result = Invoke-SSHCommand -Index 0 -Command $command

Upvotes: 20

Views: 51224

Answers (5)

bofigueiredo
bofigueiredo

Reputation: 1

The safest? I don't think so.

$result -split [Environment]::NewLine | % { Write-Host $_ }
# Doesn't work in cross-plataform 
# URI from a UNIX plataform BUT script runing in a WINDOWS plafatorm
$result = (Invoke-WebRequest -Uri $URI).Content 
$result -split [Environment]::NewLine | % { Write-Host $_ } # Doesn't work
$result -split "\r?\n|\r" | % { Write-Host $_ }             # Works 

Upvotes: -1

Paul
Paul

Reputation: 71

The safest system-agnostic way would be to use the built in environment property:

$result -split [Environment]::NewLine | % { Write-Host $_ }

Upvotes: 3

5andr0
5andr0

Reputation: 2018

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

Upvotes: 9

Scott Thompson
Scott Thompson

Reputation: 371

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

Upvotes: 27

Vesper
Vesper

Reputation: 18747

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"

Upvotes: 14

Related Questions