Tuesday, 15 June 2010

c# - Powershell XML Export-csv not appending a Hash -



c# - Powershell XML Export-csv not appending a Hash -

i new powershell, have rather weird xml according me, main objective convert xml csv, ll farther used sync database. have used powershell code extract xml hash. have problem converting them csv. export-csv writes lastly entry in hash. not sure why this, checked few other forums, -append feature in export-csv powershell 3.0 only, using 1.0..

can help me out of ?

xml :

<catalog> <segment> <segmentname>batch</segmentname> <hosts> <host> <hostname>cglist17</hostname> </host> <host> <hostname>cglist18</hostname> </host> <host> <hostname>cglist19</hostname> </host> <host> <hostname>cglist20</hostname> </host> </hosts> </segment> <segment> <segmentname>custom s2</segmentname> <hosts> <host> <hostname>cglist21</hostname> </host> <host> <hostname>cglist22</hostname> </host> </hosts> </segment> <segment> <segmentname>ecommerce</segmentname> <hosts> <host> <hostname>cglist09</hostname> </host> <host> <hostname>cglist10</hostname> </host> </hosts> </segment> </catalog>

powershell code :

[xml]$xd=gc "c:\users\sxa8869\desktop\webserv\segmentcat.xml" $nodelist = $xd.selectnodes("/catalog/segment") $masterarray = @() $masterarray = "" | select segmentname,hosts $file="c:\users\sxa8869\desktop\webserv\sha.csv" foreach ($node in $nodelist) { $hostsnode = $node.selectsinglenode("hosts") $segmentname = $node.selectsinglenode("segmentname") $masterarray.segmentname=$segmentname.get_innerxml() foreach ($hostitem in $hostsnode) { $hostnamenodes = $hostitem.selectnodes("host") foreach ($hostname in $hostnamenodes) { $masterarray.hosts=$hostname.selectsinglenode("hostname").get_innerxml() #- displays hash in table format, want format in csv $masterarray # - displaying lastly element $masterarray | export-csv "file.csv" -notype # - works, want utilize export-csv in format '"'+$masterarray.segmentname+'"'+","+'"'+$masterarray.hosts+'"' } } } required output :- ----------------- "segmentname","hosts" "batch","cglist17" "batch","cglist18" "batch","cglist19" "batch","cglist20" "custom s2","cglist21" "custom s2","cglist22" "ecommerce","cglist09" ecommerce,"cglist10"

i think you're overly complicating things. seek this:

$myxml = [xml](get-content "c:\users\sxa8869\desktop\webserv\segmentcat.xml") $file="c:\users\sxa8869\desktop\webserv\sha.csv" $myarray = @() foreach ($s in $myxml.catalog.segment) { foreach ($h in $s.hosts.host) { $myarray += new-object -typename psobject -property @{"segment name" = $s.segmentname; "host name" = $h.hostname} } } $myarray | export-csv $file -notypeinformation

c# .net powershell powershell-v2.0 powershell-remoting

No comments:

Post a Comment