0

您好,我是 Powershell 的新手,但我一直在寻找这个问题的答案,如何在 Power shell 中将 XML 数据转换为 CSV 数据。

我的 XML 数据如下所示:

<SolarWinds_SwitchPortMap Layer2Device="<info>">
     <Interfaces>
           <Interface ifIndex="<data>" CollectionTime="<data>" ConnectorPresent="<data>" Duplex="<data>" HardwareType="<data>" ifAdminStatus="<data>" ifAdminStatustest="<data>" ifAlias="<data>" ifDescr="<data>" MACAddress="<data>" MTU="<data>" ifName="<data>" ifOperStatus="<data>" ifSpeed="<data>" ifType="<data>" ifTypeName="<data>" InBitsSec="<data>" InPktsSec="<data>" LastChange="<data>" LastPacketIn="<data>" LastPacketOut="<data>" ModulePortIndex="<data>" OutBitsSec="<data>" OutPktSec="<data>" Port="<data>" TrunkPort="<data>" />
     </Interfaces>
</Solarwinds_SwitchPortMap>

我似乎无法让 Powershell 理解 xml 数据,

set-location "<program location>"
.\swspmcmd.exe <info> /xml > "<output_location>\output_data.txt"
get-content "<output location>\output_data.txt" | select -skip 17 | set-content "<xmldata_location>\xmldata.xml"
$xml = [xml] (Get-Content "<xmldata_location>\xmldata.xml")

$xml | convertto-csv -Delimiter:"," -NoTypeInformation

它只会返回“SolarWinds_SwitchPortMap”“System.Xml.XmlElement”

而且我不明白为什么,非常感谢您的帮助:)。

4

1 回答 1

2

假设您在接口节点中的数据之后,您可以执行以下操作:

[xml]$a = @"
<SolarWinds_SwitchPortMap
    Layer2Device="info">
     <Interfaces>
           <Interface 
           ifIndex="data" 
           CollectionTime="data" 
           ConnectorPresent="data" 
           Duplex="data" 
           HardwareType="data" 
           ifAdminStatus="data" 
           ifAdminStatustest="data" 
           ifAlias="data" 
           ifDescr="data" 
           MACAddress="data" 
           MTU="data" 
           ifName="data" 
           ifOperStatus="data" 
           ifSpeed="data" 
           ifType="data" 
           ifTypeName="data" 
           InBitsSec="data" 
           InPktsSec="data" 
           LastChange="data" 
           LastPacketIn="data" 
           LastPacketOut="data" 
           ModulePortIndex="data" 
           OutBitsSec="data" 
           OutPktSec="data" 
           Port="data" 
           TrunkPort="data"
           />
     </Interfaces>
</SolarWinds_SwitchPortMap>
"@

$a | select-xml  -xpath "/SolarWinds_SwitchPortMap/Interfaces/Interface" | select -ExpandProperty Node | Export-Csv -NoTypeInformation -Path ./interface.csv
于 2013-07-25T22:49:06.670 回答