How to indirectly set an environment variable

Hello.

I have the following construct in Bash, which I need to convert to Powershell:

b="Z"
export "a_"$b=100

These two statements create a global shell variable $a_Z valued 100. And the variable is marked for export.

I converted these two Bash sentences to these Powershell statements:

$b = "Z"
$__v = "a_${b}"
invoke-expression "`$global:$__v = 100"
invoke-expression "`$env:$__v = `$global:$__v"

Where __v is the “indirect” variable name. I end up with a global variable $a_Z, which is also copied to the $env environment variables, so that it is accessible to other C# programs, say.

I know that the tthird line can be written as:

New-Variable -Name $__v -Value 100 -Scope Global 

But New-Variable can’t be used to create variable in the $env name space.

Is there a more elegant way to achieve this?

Thank you!

You are just trying to set an environment variable a_Z to 100? Perhaps you can use the variable provider like this.

Push-Location env:
New-Item a_Z -Value 100
Pop-Location

Provide part of the name via a variable you can do that as well.

$b = "Z"
Push-Location env:
New-Item "a_$b" -Value 100
Pop-Location

now you have $env:a_Z set to 100.

Thanks, I did not know that New-Item could create a env: entry! Good trick. Not really shorter, but way more elegant. JL

Note that we can also do this:

$b = "Z"
New-Item -Path "env:a_$b" -Value 100
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.