Reading Multiline Text

by Jan 23, 2015

PowerShell 3.0 and later

Sometimes you will stumble across tips like the following one:

$FilePath = "$env:SystemRoot\WindowsUpdate.log"

$ContentsWithLinebreaks = (Get-Content $FilePath) -join "`r`n" 

Can you guess the purpose? Get-Content by default returns a string array with individual lines, and the operator –join can convert an array to a string.

Beginning in PowerShell 3.0, there is a parameter for this: -Raw. It is much faster than the old approach and should produce the very same result:

$FilePath = "$env:SystemRoot\WindowsUpdate.log"

$ContentsWithLinebreaks = (Get-Content $FilePath) -join "`r`n"

$ContentsWithLinebreaks2 = Get-Content $FilePath -Raw

$ContentsWithLinebreaks -eq $ContentsWithLinebreaks2

When you try the code, it turns out that $ContentWithLinebreaks and $ContentWithLinebreaks2 may not be equal, though. The only difference may be a trailing line break in $ContentsWithLinebreaks2:

 
PS> $ContentsWithLinebreaks -eq $ContentsWithLinebreaks2.TrimEnd("`r`n")
True

PS>
 

Twitter This Tip! ReTweet this Tip!