Calling/Setting a variable with a variable in the name
Try creating the variable like so:
New-Variable ${summary}_${count} -Value @{}
You can see how PowerShell is interpreting your original like so:
Write-Host $summary_$count
If you want to access that variable's value later using the constituent variables then access it like so:
$ht = Get-Variable ${summary}_${count}
Or just grab it from New-Variable with -PassThru e.g.:
$ht = New-Variable ${summary}_${count} -Value @{} -PassThru
$ht.Add($name, $value)
All that considered, it's not clear why the variable referring to the hashtable needs to be dynamically named. Another approach would be to create a hashtable of hashtables e.g.:
$ht = @{"${summary}_${count}" = @{}}
$ht["${summary}_${count}"].Add($name, $value)
user1403741
Updated on June 14, 2022Comments
-
user1403741 almost 2 years
I'm trying to populate a hashtable dynamically.
Create empty hashtable (this works fine)
New-Variable -Name $summary_$count -Value @{}
Now add to this hashtable (this doesn't work)
${summary_$count}.Add($name, $value)
The problem is it doesn't read ${summary_$count} as my previously set variable name. Just for clarification this is running through a counter so I'll ultimately end up with
$summary_01 $summary_02
etc, etc.
-
user1403741 almost 11 yearsThanks for the reply. I mentioned in the post that I don't have any issue creating the empty hashtable. It calling that variable later that's the problem, because I don't know how to reference a variable name that contains a variable in it. Where you have $ht that is a know constant that you came up with. I don't have that in my script, I have no way of knowing that since I'll be looping through things, all variables will need to be dynamic.
-
user1403741 almost 11 yearsThanks for the reply, you'll notice in the post I know how to create the variable, is referencing it after the fact that's the problem.
-
user1403741 almost 11 yearsThe reason I'm figuring out all these variables is to create objects dynamically based on contents of log files. Yes, my problem here is how to access the new variable that has a variable in it's name.
-
E.V.I.L. almost 11 years
Set-Variable
is how you access it. -
Keith Hill almost 11 yearsThen use the
Get-Variable ${summary}_${count}
approach. -
Jackie almost 11 yearsok, please do as Keith wrote,
get-variable
. And please remember$summary_$count
will be regarded as$sumary_
concat$count