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
}

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
    }

  4. Jeff
    November 29, 2018 at 7:09 pm

    I’m trying to read in all lines after a match. I can’t do anything with it because it’s making it one big multi-line string.

    $LATESTEVENTS = @(Get-Content $CLRPT | Select-String “$LASTENTRY” -Context 0,$LINECOUNT)

    I’m trying to parse the “$LATESTEVENTS” but I can’t. I tried using the here-string, but that doesn’t work either. What am I doing wrong? How can I make it so that each line is a separate element of the array?

    • November 29, 2018 at 10:07 pm

      Select-String actually returns objects of type MatchInfo.

      > (Get-Content “some-file.txt” | Select-String “searchterm” -Context 0,2 | Select-Object -First 1).GetType()
      IsPublic IsSerial Name BaseType
      ——- ——– —- ——–
      True False MatchInfo System.Object

      So you need to iterate over the result of select string and turn the matchinfo into a string which then can be separated into lines. Maybe using something like:

      Get-Content “some-file.txt” | Select-String “searchterm” -Context 0,2 | Foreach-Object { $_.ToString() -split “`r`n” }

  1. No trackbacks yet.

Leave a comment