Variable For Variable Property

This is probably the incorrect terminology, but I’d like to use a variable for a variable property (using ‘property’ for the string ‘.configuration.appSettings.add’).

For example,

Instead of

$ConfigFilePath = "D:\Config\config.xml"

[xml]$XML = Get-Content $ConfigFilePath

$KeyValue = $XML.configuration.appSettings.add | Where-Object { $_.key -eq "$key" } | Select-Object -ExpandProperty value

I’d like to use:

$ConfigFilePath = "D:\Config\config.xml"

[xml]$XML = Get-Content $ConfigFilePath

$NodeLocation = "configuration.appSettings.add"

$KeyValue = $XML.$NodeLocation | Where-Object { $_.key -eq "$key" } | Select-Object -ExpandProperty value

However, the latter does not work.

I’ve tried several variations of double/single quotes around $NodeLocation, but the KeyValue is not being picked up correctly.

Any help is appreciated.

I believe Select-XML will give you what you need.

I guess, this will do:

$KeyValue = iex "`$XML.$NodeLocation" | Where-Object etc...  # notice the grave accent

:black_small_square:

recursive properties does not supported in $object.$property notation

you can use Select-Xml, Invoke-Expression

or check this topic for workaround if you plan to use it not only for xml
https://powershell.org/forums/topic/dynamically-build-an-object-based-on-another-object-and-a-string/#post-38614

Excellent, that works! Curious why you need invoke-expression though.