19

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

Ankita13
  • 469
  • 2
  • 7
  • 21

3 Answers3

18

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

Vesper
  • 18,599
  • 6
  • 39
  • 61
  • Thanks for the reply Vesper.. But will it not create a permanent variable instead of temporary one? – Ankita13 Jun 18 '15 at 09:46
  • I guess process level should create a temoporary one ? – Ankita13 Jun 18 '15 at 09:47
  • If your variable would be of user scope, it'll be "permanent", at least reboot-presistent, until nullified. If your variable will be of process scope, it'll be temporary but available if you launch a process (`cmd.exe` tested) from within Powershell process where this variable was declared. – Vesper Jun 18 '15 at 09:50
16

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")

fredericrous
  • 2,833
  • 1
  • 25
  • 26
  • Using `Set-Item` is the best answer here. The advantage of `Set-Item` is that it is cross platform and will work on Linux machines running PowerShell 7. The `[Environment]::SetEnvironmentVariable()` approach will only work for windows machines since it relies on a .NET Framework class. – Joseph Gast Oct 29 '22 at 00:02
  • But you could install .Net Framework on your linux tho? https://dotnet.microsoft.com/en-us/download idk if I should edit my answer. on linux env, I use zsh, and on mac fish shell :P – fredericrous Nov 03 '22 at 17:32
12

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

Peter Hahndorf
  • 10,767
  • 4
  • 42
  • 58