0

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.

4
  • What are you trying to do exactly? What are you trying to accomplish? Commented Jul 25, 2014 at 16:31
  • I just want to have all these variables in one unique array. Commented Jul 25, 2014 at 16:35
  • Is there a specific reason you are using the single characters as variable names? Does it mean something in your context? Commented Jul 25, 2014 at 16:36
  • Well, in fact, it's just a "training" for me, it's just for personal purpose. Commented Jul 25, 2014 at 16:37

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Absolutely! Thanks! I know it's a bad way, but I am doing some comparaisons between "bad" and "good" practices with Measure-Command, etc. I would never do that in production obviously, it's just for personal purpose.
0

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?

Comments

0

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.

1 Comment

Thanks for your reply. Yes it works with hashtables, but I would like to keep my original structure, I want to generate variables from A to Z and then add to an array and read that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.