Home > Uncategorized > Powershell: Iterate lines in a multiline string

Powershell: Iterate lines in a multiline string

When applying the get-content command to a text file, it will produce a separate string object for each line, making it easy to process the lines individually:

Get-Content “myfile.txt” | ForEach-Object {
# process line
}

When the text is specified within a script, for example using the here string syntax, only one string is produced. Thus the following is invalid:

@”
Line 1
Line 2
Line 3
“@
| ForEach-Object {
# process line not possible – the entire multiline string is passed
}

In this case the split-string commandlet comes to rescue:

@”
Line 1
Line 2
Line 3
“@
| Split-String -separator “`r`n” | ForEach-Object {
# process line
}

Advertisements
Categories: Uncategorized
  1. Angry User
    July 25, 2013 at 12:10 pm

    PS C:\Test> Split-String
    The term ‘Split-String’ is not recognized as the name of a cmdlet, function, script file, or operable program

  2. Satisfied User
    July 25, 2013 at 12:15 pm

    Solution:
    $array = $StringTextWithLines.Split(“`n”)

    • July 26, 2013 at 10:51 am

      Split-String is from the powershell community extensions module (pscx). Of course I should have mentioned this – sorry about that… and [string]::split does the job too as you suggested.

    • KERR
      September 22, 2015 at 7:18 am

      Thanks! $array = $StringTextWithLines.Split(“`n”)

      works nicely.

  3. September 25, 2013 at 10:44 pm

    [string]::split is a little bit inconvenient and I realized there is another alternative:

    @”
    Line 1
    Line 2
    Line 3
    “@ -split “`r`n” | ForEach-Object {
    # process line
    }

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: