Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create an environment variable?

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

like image 314
Ankita13 Avatar asked Jun 18 '15 09:06

Ankita13


People also ask

Can environment variables be dynamic?

An environment variable is a dynamic-named value that can affect the way running processes will behave on a computer. They are part of the environment in which a process runs.


3 Answers

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

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

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

like image 35
fredericrous Avatar answered Sep 19 '22 05:09

fredericrous


[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).

like image 126
Vesper Avatar answered Sep 23 '22 05:09

Vesper


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

like image 10
Peter Hahndorf Avatar answered Sep 20 '22 05:09

Peter Hahndorf