You are not logged in.
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
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
Thank you. I understand the invoke-expression cmdlet now. Very useful.
Offline