如何使用 Powershell 将 XML 正确导出到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33830917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:09:43  来源:igfitidea点击:

How to properly export XML to file using Powershell

xmlpowershellpowershell-3.0

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

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

使用[XML]$Var = Get-Content -Path $PathToAnyValidXML我无法正确导出其内容作为源导入任何有效的 XML 文件。

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

使用Set-Content SomePath $Var,文件以 System.Xml.XmlDocument 作为内容结尾。

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

使用$Var | Export-Clixml SomePath,文件以 XML 中的原始 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)

将原始 XML 正确写入文件的正确方法是什么?(在将 $PathToAnyValidXML 导入到 Powershell 上的变量后,获取与 $PathToAnyValidXML 上完全相同的内容)

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

如果我们需要使用 XPath 或 Objects,请尽可能提供两种方法的示例。

回答by Hamza

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

由于您使用 [XML] 将文件作为 XML 对象导入,因此您应该使用Save()Mathod以这种方式导出它。

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

I hope this helps

我希望这有帮助

回答by Farzad

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

我正在使用Pscx安装了 PowerShell 扩展 ( ) 的PowerShell 5.1 ,我发现一种方便的方法是执行此操作:

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

回答by Tim Ferrill

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

试试`Out-File,看看它是否符合你的要求。

$Var | Out-File SomePath