user3140531
user3140531

Reputation: 3

Value of a Variable as Part of the Name of a Variable

I'm still kind of new to Powershell and I want to know if it's possible to use the value of a variable as a part of the variable name.

$a = "Stuff";
$abc???_def;  # ??? = It's where I want to use $a

Upvotes: 0

Views: 173

Answers (2)

mjolinor
mjolinor

Reputation: 68341

You can do this with New-Variable:

$a = "Stuff"
New-Variable -Name "abc$($a)_def" -Value 'This is abcStuff_def'
Get-Variable abc*


Name                           Value                                                                 
----                           -----                                                                 
abcStuff_def                   This is abcStuff_def                                                  

But I suspect a hash table might be a better choice:

$abc = @{}
$a='Stuff'
$abc.$a = 'This is abcStuff_def'
$abc


Name                           Value                                                                 
----                           -----                                                                 
Stuff                          This is abcStuff_def                                                  

Upvotes: 2

Jordan
Jordan

Reputation: 1433

Looks like the way to do it is to use New-Variable syntax.

For your example, you would do

New-Variable "abc&a_def" "value"

For more info, see http://technet.microsoft.com/en-us/library/hh849913.aspx

Much credit goes to fsimonazzi for his answer to this question: Powershell, how do I increment variable names?

Upvotes: 0

Related Questions