2

I am trying to print the key value pair from Data Object type XML using a Powershell script.

<?xml version="1.0"?>
    <Objects>
      <Object Type="System.Management.Automation.PSCustomObject">
        <Property Name="Display" Type="System.String">Microsoft</Property>
        <Property Name="Service" Type="Microsoft.Management.Service">Database</Property>
      </Object>
      <Object Type="System.Management.Automation.PSCustomObject">
        <Property Name="Display" Type="System.String">Microsoft</Property>
        <Property Name="Service" Type="Microsoft.Management.Service">RPC</Property>
      </Object>
    </Objects>

Here is the script used.

[xml]$file = Get-Content C:\xml-report.xml

foreach ($obj in $file.Objects.Object) {
    echo $obj.Display;
echo $obj.Service;
}​

How should I iterate through each key (Display, Service) and print only the values of those- i.e

Microsoft 
Database 
Microsoft 
RPC 

The output which I get now is as below. Could someone help me here?

Object
Object
Object
1
  • $File.SelectNodes('/Objects/Object/Property')|%{$_.'#text'} Commented Nov 12, 2015 at 10:14

3 Answers 3

3

As you are trying to explicitly access the properties with name Service and Display, here is a solution to directly access those, in case your xml file contains more elements you're not concerned with:

foreach ($obj in $file.Objects.Object.Property) {
  if('Display','Service' -contains $obj.Name) {
    write-output $obj.'#text'
  }
}

Or in one line:

$file.Objects.Object.Property | ? { 'Display','Service' -contains $_.name } | Select '#text'
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Arco.. is it possible to map the value of Display and Service against each other. For example - if i wanted to output as -- "the Service "Database" belong to the Display "Microsoft"".. Sorry if that sounds another question, but just wanted to check.
It is possible, and it is a different question to the one that is here, so please ask a new one if you can't figure it out on your own. A hint is to iterate over the $file.objects.object and assign variables such as: $service = $obj.Property | ? { $_.name -eq 'Service' }
0

You were just omitting the Property element. Your loop would work with a slight modification:

[xml]$file = Get-Content "C:\temp\xml-report.xml"

foreach ($obj in $file.Objects.Object) 
{
    $obj.Property | % { $_.'#text' }
}

Comments

0

If you are using Powershell version 3 or above you could try use this:

[xml]$file = Get-Content C:\xml-report.xml
$file.Objects.Object.Property.'#text'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.