I have a small powershell script which reads a document with UTF8 encoding, makes some replacements in it and saves it back which looks like this:
(Get-Conte
[IO.File]::WriteAllText()
assumes that $content
is a single string, but Get-Content
produces an array of strings (and removes the line breaks from the end of each line/string). Mangling that string array into a single string joins the strings using the $OFS
character (see here).
To avoid this behavior you need to ensure that $content
already is a single string when it's passed to WriteAllText()
. There are various ways to do that, for instance:
Use Get-Content -Raw
(PowerShell v3 or newer):
$content = (Get-Content $path -Raw) -replace 'myregex', 'replacement'
Pipe the output through Out-String
:
$content = (Get-Content $path | Out-String) -replace 'myregex', 'replacement' -replace '\r\n$'
Note, however, that Out-String
(just like Set-Content
) adds a trailing line break, as was pointed out in the comments. You need to remove that with a second replacement operation.
Join the array with the -join
operator:
$content = (Get-Content $path) -replace 'myregex', 'replacement' -join "`r`n"