Accessing a variable with a variable

Welcome Forums General PowerShell Q&A Accessing a variable with a variable

This topic contains 1 reply, has 2 voices, and was last updated by

 
Participant
5 years, 9 months ago.

  • Author
    Posts
  • #6937

    Participant
    Points: 0
    Rank: Member

    So I need to create a number of empty hashtables and then populate them with data.  The number of hashtables to create and the data to populate them with will all be determined based on the content of a log file (so I don't know what they will be beforehand, which means no hard-coding the variable names during creation or later when trying to access them).

    We'll just create one hashtable here for simplicity sake.

    $count = 1

     

    New-Variable -Name $summary_$count -Value @{}

    So we just created the variable $summary_1

    My question is, how do I access it now using $count and not a 1 in order to add data to it? Normally you would be able to run

    $summary_1.Add($name, $value)

    to add to the hashtable.  But I need to be able to do something like this

    $summary_$count.Add($name, $value)

  • #6944

    Participant
    Points: 1
    Rank: Member

     The issue you want to address is accessing a variable from a computed name. It's actually quite easy. Here's an example:

    $Count = 1
    $Prefix = 'Summary'
    New-Variable -Name "$Prefix`_$Count" -Value @{}
    $Summary_1.GetType()
    IsPublic IsSerial Name                BaseType
    ——– ——– —-               ——– 
    True     True     Hashtable          System.Object

    (Get-Variable -Name "$Prefix`_$Count" -ValueOnly).GetType()
    IsPublic IsSerial Name                BaseType
    ——– ——– —-               ——– 
    True     True     Hashtable          System.Object

     

     

The topic ‘Accessing a variable with a variable’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort