Author Posts

December 21, 2016 at 9:08 pm

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.

December 21, 2016 at 10:02 pm

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

December 22, 2016 at 3:00 am

I guess, this will do:

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

December 22, 2016 at 6:55 am

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

Dynamically build an object based on another object and a string

December 22, 2016 at 6:02 pm

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