Monday, March 29, 2010

Dynamic Variable Values

Once again, my good friend from Texas asked me for a little PowerShell assistance. Being an old Cold Fusion junkie, he sent me his cryptic CF code:

Disclaimer (Blogger hates Angle Brackets)
cfset variable1="blah"
cfset var2="yada"

This statement would've then returned the value of "#blahyada#"
cfoutput #Evaluate("#variable1#")var2# cfoutput

It is basically a self-renaming variable based on the value of another variable - no idea if PowerShell can do that.

After my brief Cold Fusion viewing induced nausea subsided, I decided to help him. This is the sample I sent him:
$DallasAddress = "123 Cowboy Ave."
$ColumbusAddress = "456 Hayes St."
$ClevelandAddress = "910 Kosar Blvd."

$loc = "Dallas"
# Returns "123 Cowboy Ave."
(Get-Variable ($loc+"Address")).value

He is now happy and has learned a little bit more PowerShell. As for me, he has added yet another 6 bottles of my favorite beverage to the till.


Anonymous said...

In order to get this working in my script, I had to do the following:

# defined variables
$columbusZip = "43210"
$loc = "Columbus"

$(get-variable -name ($(${loc})+'Zip')).Value


Wes Stahler said...

Blogger lost some formatting when I pasted. Thanks for bringing it to my attention.

Robert said...

You can omit the parentheses by using Get-Variable's ValueOnly flag:

Get-Variable "${loc}Address" -ValueOnly