Variable For Variable Property

This topic contains 4 replies, has 4 voices, and was last updated by  Brandon Lashmet 1 year, 3 months ago.

  • Author
  • #60672

    Brandon Lashmet

    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.

  • #60675


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

  • #60688


    I guess, this will do:

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

    • #60715

      Brandon Lashmet

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

  • #60694

    Max Kozlov

    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

You must be logged in to reply to this topic.