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.

  • Have you checked if the resulting file isn't saved as UTF-16 instead of UTF-8 ?
    – Stephane
    Commented Oct 28, 2014 at 9:58

3 Answers 3


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

If you process XML using non-XML-aware tools, you will always run this risk. If you want to do a transformation on XML, the best tool for the job is the XML transformation language, XSLT.

  • I don't disagree, and powershell has an [XML] type, but in this case it's likely that the he or she would have the same problem no matter how the data was transformed (if I'm right about the issue being encoding).
    – briantist
    Commented Oct 28, 2014 at 13:59
  • 1
    Well, we don't know how it's breaking the XML. It could be making it invalid against an external DTD or schema, for example. Encoding was just a guess. But yes, I didn't read carefully enough to work out that it would be challenge to find a document where replacing str1 by str2 causes a well-formedness error. Commented Oct 28, 2014 at 20:53

Have you tried using Import-CLIXML instead of Get-Content?
I don't know how well it handles big or complex xml files, but it's worth a shot.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .