Reputation: 2225
I have got a lot variables from A to Z.
$a = "bike"
$b = "car"
$c = "road"
...
$z = "street"
$array = @()
97..122 | %{$array += "$"+[char]$_}
$array
When I type $array, it returns me :
$a
$b
$c
...
$z
But I want to get the values of these variables, not "$a", etc.
Upvotes: 0
Views: 2010
Reputation:
You could use Get-Variable
to access the variables:
97..122 | %{$array += Get-Variable ([char]$_) -Value}
But may I suggest a different approach? Instead of making dozens of simple variables, why not use a hashtable? Something like:
$table = @{
"a" = "bike"
"b" = "car"
"c" = "road"
...
"z" = "street"
}
You can then access the values through indexing:
$table["a"] # > "bike"
$table["c"] # > "car"
Whenever have lots of simple variables that are of the form $var1
, $var2
, $var3
or $vara
, $varb
, $varc
you should stop and reconsider your design. Usually, you can make your code far more elegant by simply using one of PowerShell's containers, such as an array or hashtable, to store the values initially.
Upvotes: 0
Reputation: 36342
I think what he really wants is to add the contents of those variables to his array, which can be done with Get-Variable
as such:
$a = "bike"
$b = "car"
$c = "road"
$array = @()
97..99 | %{$array += Get-Variable -name ([char]$_) -ValueOnly}
$array
Upvotes: 2
Reputation: 2917
Try a hash:
$Hash = @{
a = "bike"
b = "car"
c = "road"
...
z = "street"
}
Outputting $Hash
gives you:
Name Value
---- -----
c road
z street
b car
a bike
Is that what you are looking for?
Upvotes: 0