Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Powershell, how do I set an environment variable by supplying the name as a $var?

Typically, in PowerShell you would use

env:VARIABLE = "Some kind of value"

But my issue is that I have the name of the variable in a string object. PowerShell does not recognize it as a string object and uses the variable name as the name of the environment variable.

For example, if I do this:

$someVariable = "MY_ENV_VAR"
env:$someVariable = "Some kind of value"

The result is $someVariable being literally defined as an environment variable instead of MY_ENV_VAR. I've tried numerous iterations of using ${} as if there were periods in the string, but nothing I have found works.

How can I use PowerShell's Env: using a string object?

like image 506
nathan Avatar asked Sep 23 '09 18:09

nathan


People also ask

How do you name environment variables?

Environment variable names used by the utilities in the Shell and Utilities volume of IEEE Std 1003.1-2001 consist solely of uppercase letters, digits, and the '_' (underscore) from the characters defined in Portable Character Set and do not begin with a digit.

How do you name a variable in PowerShell?

In PowerShell, variables are represented by text strings that begin with a dollar sign ( $ ), such as $a , $process , or $my_var . Variable names aren't case-sensitive, and can include spaces and special characters.

How do you set a variable value in PowerShell?

The command uses the Set-Variable cmdlet to create the variable. It uses the PassThru parameter to create an object representing the new variable, and it uses the pipeline operator ( | ) to pass the object to the Format-List cmdlet.


1 Answers

The "Env" drive is a provider so you can use the *-Item cmdlets on it e.g.:

New-Item env:\$someVariable -Value "some kind of value"

like image 97
Keith Hill Avatar answered Oct 14 '22 23:10

Keith Hill