1

We have bash indirect expansion variables as follows ${!variable}

Is there any equivalent syntax in powershell?? If no, is there any workaround?

Adding Example $username_master="SomeValue"

$branch="master"

$name="username_"+$branch

$value=$($name) --> Here it should resolve $name -> username_master then should resolve $username_master -> "SomeValue".

Thus echo $value should output "SomeValue"

The same can be achieved in bash by ${!value} which outputs "SomeValue", how to achieve the same in powershell?

Thanks in advance

vinu vizal
  • 25
  • 5
  • from what i can tell, you are talking about accessing the parameters passed to a function. if that is the case, then take a look at the following automatic variables - `$PSBoundParameters` & `$Args`. you may also want to look at `ValueFromRemainingArguments`. parameter attribute. – Lee_Dailey Dec 13 '19 at 01:16
  • Please [format your code and sample input/output properly](http://meta.stackexchange.com/a/22189/248777). – mklement0 Dec 13 '19 at 04:19

1 Answers1

3

As you mention, we can say in bash as:

a="hello"
ref="a"
echo "${!ref}"

which outputs:

hello

The equivalence in PowerShell will be:

$a = "hello"
$ref = [ref]$a
echo $ref.Value

which also outputs:

hello

I hope this is what you want.

[EDIT]

According to the OP's example, how about:

$username_master = "SomeValue"
$branch = "master"
$name = "username_" + $branch
Get-Variable -Name $name -valueOnly

which outputs:

SomeValue

You can also assign a variable to the result with:

$value = Get-Variable -Name $name -valueOnly
echo $value

yields:

SomeValue

Hope this helps.

tshiono
  • 21,248
  • 2
  • 14
  • 22
  • Lets Take this example $username_master="SomeValue" $branch="master" $name="username_"+$branch --> here after it resolves to username_master it should fetch the value of $username_master to $name echo $name should output "SomeValue" Could you please suggest a solution?? Thanks – vinu vizal Dec 13 '19 at 03:25
  • @vinuvizal Thank you for the response. I've updated my answer by adding a solution for your example. BR. – tshiono Dec 13 '19 at 03:48
  • Thanks! Tested it working perfectly fine :) – vinu vizal Dec 13 '19 at 03:52
  • @vinuvizal Thanks for the immediate testing and feedback. Good to know it works. BR. – tshiono Dec 13 '19 at 04:11