20

Importing any valid XML file as source using [XML]$Var = Get-Content -Path $PathToAnyValidXML I am unable to export it's content properly.

Using Set-Content SomePath $Var , the file ends with System.Xml.XmlDocument as content.

Using $Var | Export-Clixml SomePath , the file ends with the original XML inside an XML

What is a correct method to write raw XML to a file properly ? (Get the exact same content that was on $PathToAnyValidXML once it was imported to a variable on Powershell)

If we need to use XPath or Objects, provide example with both method if possible.

4 Answers 4

32

Since you imported the file as an XML Object using [XML], to export it that way you should use the Save() Mathod.

$VAR.save("c:\works.xml")

I hope this helps

Sign up to request clarification or add additional context in comments.

2 Comments

I should have used Import-Clixml in the first place instead of get-content + [XML]$xxx to get the way I was doing it working, correct ?
Sorry for the late answer, but yes you're right. import-clixml will import an XML object, that you can work with easily, get-content wont do that for you.
4

I'm using PowerShell 5.1 with PowerShell Extensions (Pscx) installed, and a convenient way that I found is to do this:

$Var | Format-Xml | Out-File $file_path

2 Comments

using Powershell 5.1, and getting the error "Format-Xml" is not recognized ...
Hey @Pac0, I'm sorry I didn't realize at the time, but Format-Xml comes from the PowerShell extensions module. I think it's a good idea to install them because they are very useful
1

$xml.OuterXml | Out-File test.xml

Comments

-5

Give `Out-File a try and see if that does what you're after.

$Var | Out-File SomePath

1 Comment

Out-File doesn't keep formatting on the xml, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.