No because performance issue is not with Get-Content -Raw but rather with ForEach-Object…
When you run Get-Content -Raw what happens is that entire file content is returned as a single line rather than multiple lines, and this happens only once.
Reason why you’re able then to parse line by line is because when -Raw is specified line breaks are preserved with \n character, that’s how multiline regex option recognizes a new line in a bulk that was returned.
Knowing this it follows that Get-Content -Raw is a single operation, it’s not iterated over and over so it’s not a performance issue.
ForEach-Object is however needed only once, if you save data to variable and run ForEach-Object multiple times like this:
$data = Get-Content -LiteralPath $file -Raw
$data = $data | ForEach-Object { /* regex operation 1 */ }
$data = $data | ForEach-Object { /* regex operation 2 */ }
$data = $data | ForEach-Object { /* regex operation 3 */ }
$data = $data | ForEach-Object { /* regex operation 4 */ }
This are obviously 4 ForEach-Object operations + 4 regex operations which is 8 operations in total, in comparison to my sample code which uses only one ForEach-Object + 5 regex operations which is 6 operations in total.
Therefore it’s 8 vs 6 operations or 40% improvement.
You can find out many discussions about ForEach-Object penalizing perfomance ex:
Speed up Foreach-Object and Where-Object by using Steppable Pipeline · Issue #10982 · PowerShell/PowerShell (github.com)
Note that you could omit -Raw and regex multiline option like this:
$data = Get-Content -LiteralPath $file | ForEach-Object {
[regex]::Replace($_, "!|^rem|^SETLOCAL|^ENDLOCAL", $Evaluator)
}
However this is much worse because now ForEach-Object will run as many times as there are lines in a file, resulting in much more operations and worse performance.
btw. here is an improvement of my previous sample code, it doesn’t use ForEach-Object at all:
$data = Get-Content -LiteralPath $file -Raw
$data = [regex]::Replace($data, "!|^rem|^SETLOCAL|^ENDLOCAL", $Evaluator, [RegexOptions]::Multiline)
# save modifications
Set-Content -Value $data -LiteralPath $file
This is now only 5 operations and a 50% improvement vs previous 40%.
So I suggest you update your code for this small improvement.