You are not logged in.

#1 24 Feb 2017 23:13

Cornbeetle
New Member
Registered: 05 Oct 2016
Posts: 3

Variable of a variable, please help me understand.

Why doesn't this code work?

I'm used to BATCH where delayed expansion will allow me to create a variable inside a variable like this:

set var1=a
set var2=var1
echo "!%var2%!"

The output above should be

echo "a"

In this powershell code, why doesn't the same logic work?

$last = "surname"
$userProperty = "last"
write-output "$($userProperty)"

Offline

#2 25 Feb 2017 10:09

Simon Sheppard
Admin
Registered: 27 Aug 2005
Posts: 1,130
Website

Re: Variable of a variable, please help me understand.

Cornbeetle wrote:
write-output "$($userProperty)"

The above displays "last" because it is simply evaluating the contents of $userProperty
what you need is to actually execute $userProperty like it was a command, and that is done with Invoke-Expression.

so you might expect this to work,

Invoke-Expression "$$($userProperty)"

but the doubled $$s will be evaluated as Text so you need to escape the first one:

Invoke-Expression "`$$($userProperty)"

Be aware that Invoke-Expression is quite a powerful/dangerous cmdlet, make sure your inputs have been sanitised.

Offline

#3 27 Feb 2017 15:08

Cornbeetle
New Member
Registered: 05 Oct 2016
Posts: 3

Re: Variable of a variable, please help me understand.

Thank you. I understand the invoke-expression cmdlet now. Very useful.  big_smile

Offline

Board footer

Powered by