Reading XML in PowerShell

by Oct 5, 2011

Hi there,

I'm fairly new to PowerShell and I'm trying to read the value of an attribute from a collection of nodes in an XML file.

Here's the structure from the XML file that I'm reading from:

<Inventory>
 <Permissions>
  <Permission Principal="DOMAINAdmin-Group" Role="Admin" />
  <Permission Principal="DOMAINAdmin-Group" Role="PowerUser" />
  <Permission Principal="DOMAINAdmin-Group" Role="User" />
  <Permission Principal="DOMAINPower-Group" Role="PowerUser" />
  <Permission Principal="DOMAINPower-Group" Role="User" />
  <Permission Principal="DOMAINUser-Group" Role="User" />
 </Permissions>
</Inventory>

What I want to be able to do is read the Principal attribute and end up with a list that looks like the following:

DOMAINAdmin-Group
DOMAINPower-Group
DOMAINUser-Group

You'll notice that in the XML document, there are multiple nodes with the same value for the Principal attribute. In the final list that I want to produce, I only want the unique values, but at this stage I'm trying to understand how to read the actual Principal attribute.

I came across this site that I thought would solve my problem >http://powershell.com/cs/blogs/ebook/archive/2009/03/30/chapter-14-xml.aspx#accessing-attributes

.. however when I use $xmldata.Inventory.Permissions.Permission.GetAttribute("Principal"), I get an error in PowerShell saying:

Method invocation failed because [System.Object[]] doesn't contain a method named 'GetAttribute'.
At script.ps1:95 char:55
+ $xmldata.Inventory.Permissions.Permission.GetAttribute <<<< ("Principal")
+ CategoryInfo : InvalidOperation: (GetAttribute:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound

Is anyone able to tell me what I'm doing wrong?

Thanks,
Chris.