Hashtable with Dynamic Key

Hi All,

I’ve run into an issue which is killing my productivity! I’m trying to create a hash table with a dynamic key name. I’m not sure if this isn’t possible, or if I’m not doing it correctly.

Here’s what works. There ‘name’ is static.

$name = "Roy"
$age = 20
weight = 150

$hash = @{
    name = @{
        Age = $age
        Weight = $weight
    }
}

$hash.Name.Age
20

Here’s what won’t work

$name = "Roy"
$age = 20
weight = 150

$hash = @{
    $name = @{
        Age = $age
        Weight = $weight
    }
}

$hash.Roy.Age
(No output)

Is it possible to dynamically use a variable as a key in powershell? If not, what are some other options?

Second one works fine for me (ignoring the missing $ in front of weight).

Yeah, the examples worked for me as well I just learned. It mirrored the problem I had in my real code. The issue was that the real code didn’t have the $name string trimmed (trim()). I can’t believe how much time I spent on this.

Thanks, and sorry for the extraneous post.

1 Like

Happens to all of us! :slight_smile: