Powershell – Replacing a string in an XML with Powershell causes MALFORMED XML

powershellstringsxml

I have a rather large XML file that I need to replace some connection strings within.

I use the following code to replace the strings:

$temp = Get-Content .\bigxmlfile.xml
$temp.replace("STRING1","STRING2") | out-file .\bigxmlfile.xml -force

This changes the strings just fine but for some reason ALWAYS ends up breaking the XML.
I'm having trouble figuring out why.

Best Answer

Out-File is writing a Unicode file by default. Use -Encoding to fix it:

$temp = Get-Content .\bigxmlfile.xml
$temp.replace("STRING1","STRING2") | out-file .\bigxmlfile.xml -force -encoding ascii

Alternatively, use Set-Content:

$temp = Get-Content .\bigxmlfile.xml
$temp.replace("STRING1","STRING2") | set-content .\bigxmlfile.xml -force