解析多个XML节点值以导出到CSV

时间:2020-03-04 16:04:07

标签: xml powershell

尝试从IIS xml配置文件中获取以下节点的值

Location Path =
allowUnlisted =
ipAddress =
subnetMask =

我挂在子网掩码部分

@Theo已经提供了大多数解决方案,我尝试的所有操作都将整个子网阵列都转储到了子网字段中

[xml]$xmlfull = (Get-Content .\Sample.xml)
$result = $xmlfull.configuration.location | ForEach-Object {
    $client        = $_.path
    $allowUnlisted = $_.'system.WebServer'.security.ipSecurity.allowUnlisted
    $subnets = $($_.'system.WebServer'.security.ipSecurity.add.subnetMask)
    $ips = $($_.'system.WebServer'.security.ipSecurity.add.ipAddress)
    foreach ($ip in $ips ) {
        [PsCustomObject]@{
        ExampleClinet = $client 
        AllowUnlisted = $allowUnlisted
        IPAddress     = $ip
        Subnet        = 
       }
      }
    }

# output on screen
$result

# output to CSV file
$result | Export-Csv -Path '\test.csv' -NoTypeInformation

示例XML

 <configuration> 
     <location path="Example/5192_proxy">
            <system.webServer>
                <security>
                    <ipSecurity allowUnlisted="false">
                        <add ipAddress="10.10.100.0" subnetMask="255.255.252.0" allowed="true" />
                        <add ipAddress="10.10.48.0" subnetMask="255.255.240.0" allowed="true" />
                        <add ipAddress="10.10.100.0" subnetMask="255.255.252.0" allowed="true" />
                        <add ipAddress="192.168.63.97" subnetMask="255.255.255.224" allowed="true" />
                    </ipSecurity>
                </security>
            </system.webServer>
        </location>
        <location path="Example/3796_Proxy">
            <system.webServer>
                <security>
                    <ipSecurity allowUnlisted="false">
                        <add ipAddress="192.168.30.52" allowed="true" />
                        <add ipAddress="10.10.48.0" subnetMask="255.255.240.0" allowed="true" />
                    </ipSecurity>   
                   </security>
            </system.webServer>
        </location>
    </configuration>

1 个答案:

答案 0 :(得分:1)

更改$ips变量以容纳<add ...>节点而不是ipAddress属性的值,然后可以在循环中引用这两个变量:

# ...
$ips = @($_.'system.WebServer'.security.ipSecurity.add)
foreach ($ip in $ips) {
  [PsCustomObject]@{
    ExampleClinet = $client 
    AllowUnlisted = $allowUnlisted
    IPAddress     = $ip.ipAddress
    Subnet        = $ip.subnetMask
  }
}