Skip to content
Advertisement

How to print a list of xml elements and their properties in the Powershell REPL console?

Referencing:

https://www.red-gate.com/simple-talk/sysadmin/powershell/powershell-data-basics-xml/

and:

https://stackoverflow.com/a/65264118/4531180

how is a list of elements and their properties printed?

JavaScript

Advertisement

Answer

To address the for-display formatting problem:

If you look closely at the sample output from your own answer, you’ll see that even though the display is mostly helpful, the value of the author property is author instead of showing the (presumed) first-name and last-name child-element values.

The problem is that PowerShell’s default output formatting represents child elements that have:

  • at least one attribute
  • and/or at least one child element themselves

by the element’s name only.

Especially with deeply nested elements this results in unhelpful output.

Workarounds, possibly in combination:

  • Access the .OuterXml or .InnerXml property of such elements, which contains the full XML text of the element with / without the element’s tags themselves.

    • This will likely only be helpful with perhaps at most another level of nesting will be visually helpful, given that the XML text is a single-line representation that is not pretty-printed.

    • You can pipe .OuterXml / InnerXml values to a pretty-printing function, which requires some extra work, however, because no such functionality is directly exposed by PowerShell.

  • Use Select-Object (or, for display purposes only, a Format-* cmdlet such as Format-Table) with calculated properties.

    • While this allows you full control over what is displayed, it is more work.

See the examples below.


JavaScript

To get a helpful representation of all <book> elements including the <author> child elements’ <first-name> and <last-name> child elements via Select-Object and a calculated property:

JavaScript

This yields (note how the author property now lists first and last name):

JavaScript

To get a helpful representation of all <book> elements via pretty-printed XML, via an auxiliary System.Xml.Linq.XDocument instance:

JavaScript

This yields (a pretty-printed XML representation):

JavaScript

Note that you could wrap the formatting code in a simple (filter) function named Format-Xml that you could put in your $PROFILE file (in Windows PowerShell, also place the Add-Type -AssemblyName System.Xml.Linq there, above it):

JavaScript

Now the formatting is as simple as:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement