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
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.
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")
[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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With