1

I would like to dynamically construct the name of an environment variable. I tried this:

$partition = $env:partition
$desiredvariable = "abc_$partition"
$desiredvalue = $env:$desiredvariable

This doesn't seem to work. Can this be done?

Thanks

2 Answers 2

4

Yes you can!

Environment variables can be manipulated using the [System.Environment]::SetEnvironmentVariable() method:

$SomeName = "test"
[System.Environment]::SetEnvironmentVariable($SomeName,"value")

You can then access it like normally:

PS C:\> $env:test
value

Or, using the GetEnvironmentVariable() method:

PS C:\> [System.Environment]::GetEnvironmentVariable($SomeName)
value
PS C:\> [System.Environment]::GetEnvironmentVariable("test")
value
Sign up to request clarification or add additional context in comments.

Comments

2

You were close.

$t='tmp'
dir env:$t

Output:

Name Value
---- ----- TMP C:\Users\ESDADMMS\AppData\Local\Temp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.