PowerShell XML Data
XML data is text that stores values inside named elements. Dot names and XPath queries read those values without printing the whole document.
Cast text to XML and read with dots
The [xml] cast turns a text string into XML data. Dots then walk from the root element to the value.
[xml]$book = "<book><title>Dune</title><author>Frank Herbert</author></book>"
$book.book.title
$book.book.authorFind nodes with Select-Xml
Select-Xml takes an XPath query and returns the matching nodes. The Node InnerText values hold the titles.
[xml]$catalog = "<catalog><book><title>Dune</title></book><book><title>Emma</title></book></catalog>"
($catalog | Select-Xml -XPath "//title").Node.InnerText -join ", "Change a value and print the new value
Assign a new value through the same dot path. Print only the changed value, never the whole document.
[xml]$book = "<book><title>Dune</title><price>12</price></book>"
$book.book.price = "15"
$book.book.title
$book.book.priceExample
[xml]$catalog = "<catalog><book><title>Dune</title><price>12</price></book><book><title>Emma</title><price>9</price></book></catalog>"
$catalog.catalog.book[1].price = "10"
($catalog | Select-Xml -XPath "//title").Node.InnerText -join ", "
$catalog.catalog.book[1].title
$catalog.catalog.book[1].priceKey points
- XML: text that stores values inside named elements.
- Element: a named part of XML data, like title inside book.
- Use [xml] to turn an XML text string into data PowerShell can navigate.
- Dot navigation: read an element value with dots between element names, like $book.book.title.
- Select-Xml: a command that finds XML nodes with an XPath query.
- XPath: a short query that names the nodes to find, like //title for every title element.
In this example, the catalog holds two books, and the second book price is changed to 10. Select-Xml lists both titles, and dot navigation prints the second book title and its new price.
Note
changing a value in script changes only the in-memory data, not a file on disk.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line reads the title of the first book in $catalog?