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 intended for use in puppet scenarios.

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

I'm trying to use

 $env:FACTER_$Variable_Name = $Variable_Value 

But $ is not an acceptable syntax. When I enclose it in double quotation marks, the value of the variable will not be passed. Any suggestion on how to use it dynamically.

Thanks at Advance

+6
source share
3 answers

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

This syntax allows you to use expressions instead of "TestVariable" and should be sufficient to create a profile environment variable. The third parameter can be "Process", this makes new vars visible in Get-ChildItem env: or "Machine" - this requires administrative rights to set the variable. To get such a variable, use [Environment]::GetEnvironmentVariable("TestVariable", "User") (or the corresponding area if you select another).

+8
source

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 use the New-Item cmdlet to add a new variable, I just need to specify -itemtype and -path

+6
source

In Powershell 5, I use Set-Item to dynamically change the environment variable in the current shell:

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

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

+1
source

Source: https://habr.com/ru/post/989333/


All Articles