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.
Using XML files is very common in the IT World and PowerShell gives us a possibility to manipulate XML files. To export XML file in PowerShell we use Export-Clixml CmdLet likewise to import the XML file in PowerShell we use Import-Clixml CmdLet but in this article, we will focus on exporting XML files.
Click File > Save As, and select the location where you want to save the file. , point to the arrow next to Save As, and then click Other Formats. In the File name box, type a name for the XML data file. In the Save as type list, click XML Data, and click Save.
Casting XML Strings to Objects Another way to use PowerShell to parse XML is to convert that XML to objects. The easiest way to do this is with the [xml] type accelerator. By prefixing the variable names with [xml] , PowerShell converts the original plain text XML into objects you can then work with.
The Export-Clixml cmdlet creates a Common Language Infrastructure (CLI) XML-based representation of an object or objects and stores it in a file.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With