Powershell and -replace regex against blank lines '^$'
12:23 08 Jan 2026

I like powershell's features, but not a big fan of MS Powershell documentation and supplied examples.

An internet searching for this kept coming up with how to remove when I wanted to replace empty ^$ lines with a space. My need was due to some down stream program that ignored empty lines (and not addressable) and changing them to have a single space had minimal consequences vs the losing lines.

I tend to use powershell from a DOS shell and .bat files so I typically do ...

powershell xxxxx

vs being in powershell.

Originally I was doing ...

powershell (get-content myfile.txt) -replace '^$' , ' ' > newfile.txt

and it was putting a blank at the end of every line.

What I eventually discovered was this particular variation needed a '^^$' to work when I randomly tried adding the extra ^. I then realized it was because the DOS shell was treating the single ^ as a escape character and not passing it to powershell. So effectively the ^ needed to be escape by using a double ^. Yeah, stupid me (after the fact).

I eventually also found that enclosing the powershell syntax in double quotes also allowed ^$ to work and ^^$ also still worked.

So here are the working variations ...

powershell (get-content myfile.txt) -replace '^^$' , ' ' > newfile.txt

powershell "(get-content myfile.txt) -replace '^$' , ' ' " > newfile.txt

powershell "(get-content myfile.txt) -replace '^^$' , ' ' " > newfile.txt

Maybe there are some other variations on how to do this, but hope this helps someone.

regex powershell replace