Searching XML Nodes By Attribute Name with Select-XML


Any of you say this prayer after you’ve successfully remembered how to filter by the node attribute property with Select-XML and PowerShell?

Dear God. Please let me remember this syntax the next time I’m trying to search an XML file. If you will just spare me the hours of searchig through useless blog posts and references of XPath syntax I swear I’ll be good. I’ll be a better man to those around me; I’ll live like a boy scout forever.

I’ve said it, thought it and prayed it, but I guess God wanted me to just write it down, because I can never remember it when I want to. Luckily for me, I have this blog where I can jot down simple notes like this.

To search XML nodes with an attribute, use a freaking ‘@’ to indicate attribute name

#Any XML will do
[xml]$xml = Get-Content C:\windows\starter.xml

#Find all nodes of type "component"
$xml | Select-Xml -Xpath "//component"

#Find ONLY the nodes of type "component" with an attribute of "name"
$xml | Select-XML -XPath "//component[@name]"

#And ONLY the nodes of type "component" with an attribute "name" with a value of "Microsoft-Windows-themeservice"
$xml | Select-XML -XPath "//component[@name='Microsoft-Windows-themeservice]"

Hope this helps you. If you found this post, it’s going to be a real timesaver for working with XML.