Multiline Regex in PowerShell

Get-Content produces an array of strings, where each string contains a single line from your input file, so you won’t be able to match text passages spanning more than one line. You need to merge the array into a single string if you want to be able to match more than one line:

$text = Get-Content $file | Out-String

or

[String]$text = Get-Content $file

or

$text = [IO.File]::ReadAllText($file)

Note that the 1st and 2nd method don’t preserve line breaks from the input file. Method 2 simply mangles all line breaks, as Keith pointed out in the comments, and method 1 puts <CR><LF> at the end of each line when joining the array. The latter may be an issue when dealing with Linux/Unix or Mac files.

Leave a Comment