Your pseudo could should work, as PowerShell indeed allows you to use variable references as property names.
A simplified example:
$propName = 'Year'
(Get-Date).$propName # -> e.g., 2023
(...)
, the grouping operator, even allows you to use (the return value of) expressions as property names:
# Array element as property name.
$propNames = 'Year', 'Day'
(Get-Date).($propNames[0]) # -> e.g., 2023
# Property value of another object as property name.
$propNameObj = [pscustomobject] @{ Name = 'Year' }
(Get-Date).($propNameObj.Name) # -> e.g., 2023
# Arbitrary expression as property name.
$i = 2
([pscustomobject] @{ P1 = 1; P2 = 2; P3 = 3}).('P' + $i) # -> 2
Here's a self-contained example in the context of your scenario:
# Sample input XML
[xml] $xml = '
<Products>
<Product price="20.99">Product A</Product>
<Product price="30.99">Product C</Product>
<Product price="10.99">Product B</Product>
</Products>
'
# Sort the <Product> elements by their 'price' attribute.
$attribName = 'price'
$xml.Products.Product |
# Access the 'price' property (XML attribute) via a variable value.
Sort-Object { [decimal] $_.$attribName } |
# "Append" the elements in sort order to their parent element,
# which effectively *rearranges* in them sort order.
ForEach-Object { $null = $xml.Products.AppendChild($_) }
# Display the resulting document.
# Note: [System.Xml.Linq.XDocument] is solely used for simple
# pretty-printing of the XML structure.
Add-Type -AssemblyName System.Xml.Linq
([System.Xml.Linq.XDocument] $xml.OuterXml).ToString()
Note:
- Even though it is technically an XML attribute that is sorted by, PowerShell surfaces it as a property, which it equally does for child elements - see this answer for details on this adaptation of the XML DOM (
[xml]
(System.Xml.XmlDocument
) that PowerShell automatically provides.
The above outputs the following, showing the <Product>
elements correctly sorted by price:
<Products>
<Product price="10.99">Product B</Product>
<Product price="20.99">Product A</Product>
<Product price="30.99">Product C</Product>
</Products>