JasonBluefire
JasonBluefire

Reputation: 311

Converting XML data to CSV powershell

Hello I am new to Powershell but I have looked all over for an answer to this question, how do I convert XML data to CSV data in power shell.

My XML data looks like this:

<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>

I can't seem to get Powershell to understand the xml data,

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

And it will only return "SolarWinds_SwitchPortMap" "System.Xml.XmlElement"

and I don't understand why, any help is greatly appreciated thanks :).

Upvotes: 0

Views: 4743

Answers (1)

Chad Miller
Chad Miller

Reputation: 41847

Assuming you're after the data in the interfaces node you could do something like this:

[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

Upvotes: 2

Related Questions