将XML数据转换为CSV powershell

时间:2013-07-25 19:51:02

标签: xml powershell csv

您好我是Powershell的新手,但我已经全神贯注地回答了这个问题,如何在电源外壳中将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”

我不明白为什么,非常感谢任何帮助,谢谢:)。

1 个答案:

答案 0 :(得分: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