Keep the streaming approach. It is the right choice for large files because it does not load the whole file into memory. The useful improvements are to create the regular expressions once, dispose both streams even if an error occurs, and avoid PowerShell pipeline overhead.
$reader = $null
$writer = $null
try {
$spaceRuns = [regex]::new(' {2,}')
$hasContent = [regex]::new('[^\s|]')
$reader = [System.IO.File]::OpenText('%FILE%')
$writer = [System.IO.File]::CreateText('%TEMPFILE%')
while ($null -ne ($line = $reader.ReadLine())) {
$cleaned = $spaceRuns.Replace($line, '')
if ($hasContent.IsMatch($cleaned)) {
$writer.WriteLine($cleaned)
}
}
}
finally {
if ($writer) { $writer.Dispose() }
if ($reader) { $reader.Dispose() }
}
This keeps the current behavior: runs of two or more spaces are removed, and lines containing only whitespace and | are skipped.
If you meant to reduce multiple spaces to one space, change the replacement to:
$cleaned = $spaceRuns.Replace($line, ' ')
Also make sure %FILE% and %TEMPFILE% are different paths. Writing to the same file being read can truncate the input.
Answers
Know the answer? Post it. Somebody with the same question will find it here.