Home > database >  In Powershell, how do I extract multiple values from XML
In Powershell, how do I extract multiple values from XML

Time:12-30

In this XML:

<?xml version="1.0">
<Devices ClientType="Desktop">
<Device HostName="12345-Desktop">
      <Parameter Name="DefaultEnvironment" Value="Test" />      
      <Parameter Name="WorkstationID" Value="T100" />
      <Parameter Name="WorkstationAgency" Value="A" />
      <Parameter Name="ServerIP_Trn" Value="tng.domain.com" />
      <Parameter Name="ServerIP_Stg" Value="stg.domain.com" />
      <Parameter Name="Production" Value="TRUE" />
      <Parameter Name="Training" Value="FALSE" />
      <Parameter Name="Staging" Value="FALSE" />
     </Device>
</Devices>

I'm trying to extract the hostname and WorkstationID in a single line. What I would like to see is

12345-Desktop   T100
 

This is what i've tried:

[xml]$Config = $wc.DownloadString("http://xmlsource/xmlfile.xml")
$device=$Config.Devices.Device

#to get hostname:
$devices.hostname

#To get parameters:
$devices.parameter | select Name, value | where {$_.name -eq 'WorkstationID'}

How do combine both outputs in one line like the above? Do I need to use XPath?

CodePudding user response:

You're on the right track, but you'll need a calculated property in order to reach into the array:

$devices | Select-Object -Property @(
    'HostName'
    @{
        L = 'WorkstationID'
        E = { $PSItem.Parameter.Where{ $PSItem.Name -eq 'WorkstationID' }.Value }
    }
)

e: an example using Where-Object instead from comments-

$devices | Select-Object -Property @(
    'HostName'
    @{
        L = 'WorkstationID'
        E = { ($_.Parameter | Where-Object Name -eq WorkstationID).Value }
    }
)
  • Related