Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly export XML to file using Powershell

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.

like image 382
Магисья Темная Леди Avatar asked Nov 20 '15 15:11

Магисья Темная Леди


People also ask

How do I Export XML from PowerShell?

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.

How do I Export an XML file?

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.

How do I convert XML to PowerShell?

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.

What CmdLet exports EMS output data to XML?

The Export-Clixml cmdlet creates a Common Language Infrastructure (CLI) XML-based representation of an object or objects and stores it in a file.


2 Answers

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

like image 157
Hamza Avatar answered Oct 22 '22 17:10

Hamza


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
like image 23
Farzad Avatar answered Oct 22 '22 18:10

Farzad