我对 Powershell 相当陌生,据我所知,我有相当奇怪的 xml,我的主要目标是将 XML 转换为 CSV,它将进一步用于同步到数据库。我已经使用 Powershell 代码将 xml 提取到哈希中。现在我在将它们转换为 CSV 时遇到问题。Export-csv 仅写入散列中的最后一个条目。不知道为什么,我检查了其他几个论坛,他们说 Export-csv 中的 -append 功能仅适用于 powershell 3.0,我使用的是 1.0..
你能帮我解决这个问题吗?
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>
电源外壳代码:
[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 the hash in table format, want this format in csv
$MasterArray
# - displaying only the last element
$MasterArray | export-csv "file.csv" -notype
# - this works, but i want to use export-csv to get it in this 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"