Variable For Variable Property

Tagged: , ,

This topic contains 4 replies, has 4 voices, and was last updated by Profile photo of Brandon Lashmet Brandon Lashmet 7 months ago.

  • Author
    Posts
  • #60672
    Profile photo of Brandon Lashmet
    Brandon Lashmet
    Participant

    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
    Profile photo of Ron
    Ron
    Participant

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

  • #60688
    Profile photo of Al
    Al
    Participant

    I guess, this will do:

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

    • #60715
      Profile photo of Brandon Lashmet
      Brandon Lashmet
      Participant

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

  • #60694
    Profile photo of Max Kozlov
    Max Kozlov
    Participant

    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.