How to dynamically create an environment variable?

12.4k Views Asked by At

I am using powershell script to set some environment variable--

$env:FACTER_Variable_Name = $Variable_Value

FACTER is for using these in the puppet scripts.

My problem is - the variable name and variable value both are dynamic and getting read from a text file.

I am trying to use

$env:FACTER_$Variable_Name = $Variable_Value

But $ is not acceptable syntax. When I enclose it in double quotes, the variable value is not getting passed. Any suggestion how to use it dynamically.

Thanks in Advance

3

There are 3 best solutions below

3
On BEST ANSWER

[Environment]::SetEnvironmentVariable("TestVariable", "Test value.", "User")

This syntax allows expressions in the place of "TestVariable", and should be enough to create a profile-local environment variable. The third parameter can be "Process", this makes new vars visible in Get-ChildItem env: or "Machine" - this required administrative rights to set the variable. To retrieve a variable set like this, use [Environment]::GetEnvironmentVariable("TestVariable", "User") (or matching scope if you choose another).

2
On

In pure PowerShell, something like this:

$Variable_Name = "foo"
$FullVariable_Name = "FACTER_$Variable_Name"
$Variable_Value = "Hello World"
New-Item -Name $FullVariable_Name -value $Variable_Value -ItemType Variable -Path Env:

I'm using the New-Item cmdlet to add a new variable, just have to specify the -itemtype and -path

4
On

On Powershell 5, to set dynamically an environment variable in the current shell I use Set-Item:

>$VarName="hello"
>Set-Item "env:$VarName" world

once the variable is set, you can get its value like so:

>$env:hello
world

and of course to persist the variable I use C# [Environment]::SetEnvironmentVariable("$VarName", "world", "User")