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
PS C:\Test> Split-String
The term ‘Split-String’ is not recognized as the name of a cmdlet, function, script file, or operable program
Solution:
$array = $StringTextWithLines.Split(“`n”)
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.
Thanks! $array = $StringTextWithLines.Split(“`n”)
works nicely.
[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
}
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?
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” }