Danijel de Vasco
Danijel de Vasco

Reputation: 53

Use variable in other variable name

I need values of variables which these variable names are concatened by another variable's value.

e.g.

$GV_R32_var = "testtesttest"
$m = "R32"
(Get-Variable -Name "`$GV_$($m)_var").Value

I receive following error message:

+ (Get-Variable -Name "`$GV_$($m)_var").Value
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: ($GV_R32_var:String) [Get-Variable], ItemNotFoundException
    + FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand

Upvotes: 2

Views: 112

Answers (2)

Esperento57
Esperento57

Reputation: 17472

you can do it too:

Invoke-Expression $"GV_$m`_var"

Upvotes: 0

gvee
gvee

Reputation: 17161

You're really close!

The variable name doesn't include a dollar!

So your code:

(Get-Variable -Name "`$GV_$($m)_var").Value

Becomes:

(Get-Variable -Name "GV_$($m)_var").Value

Upvotes: 4

Related Questions