Powershell无法读取xml文件?

时间:2018-07-09 15:37:51

标签: xml file powershell

我有一个Powershell脚本来读取xml文件。这是代码

$configPath = Join-Path $PSScriptRoot 'config.xml'
Write-Host $configPath
[xml]$XmlDocument = [xml](get-content $configPath)
Write-Host $XmlDocument
foreach($line in Get-Content $configPath) {
    Write-Host $line
}

当我打印$XmlDocument时,它显示为空字符串,但是该文件有效,因为当我执行for循环以一次读取第一行时,它可以工作并打印

<employees>
    <employee id="101">
        <name>Frankie Johnny</name>
        <age>36</age>
    </employee>
    <employee id="102">
        <name>Elvis Presley</name>
        <age>79</age>
    </employee>
    <employee id="301">
        <name>Ella Fitzgerald</name>
        <age>102</age>
    </employee>
</employees>

有人知道是什么问题吗?

谢谢

1 个答案:

答案 0 :(得分:1)

使用Write-Output,而不是Write-Host。我使用自己的XML文档进行了测试,[xml]$XmlDocument包含数据,但Write-Host不输出任何数据。我不确定Write-Host为什么不打印$ XmlDocument的内容,但我确定它与Write-Host周围的管道奇数有关(这会中断管道)。

几乎应该始终避免使用Write-Host来代替Write-Output。另请参阅Write-WarningWrite-VerboseWrite-ErrorWrite-Debug cmdlet,以将信息输出到STDOUT以外的其他流或直接将其输出到控制台主机。请参阅this post for more information,了解为什么应尽可能避免使用Write-Host以及它被认为是有害的。