Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Setting Environment variable for local variable

I am getting a list of values from the command line in format of key=val key=val, after splitting them down and then into key and value, I want to set an environment variable using the key.

I have tried the following code ($sstr is being set from arguments, but I have hard coded it to simplify the code), but I am getting 'unexpected token' error:

$retrievedVal = "key1=val1 key2=val2"

# Split the string, with space being the delimiter, leaving key=value
$sstr = $retrievedVal .split( " " )

foreach ( $var in $sstr )
{
    $keyvalueList = $var.split( "=" )
    $env:($keyvalueList[0]) = "Test"
}

Any suggestions to where I have gone wrong would be greatly appreciated :)

like image 957
Gemma Morriss Avatar asked Oct 13 '15 13:10

Gemma Morriss


People also ask

How do I permanently set an environment variable in PowerShell?

Using $env:Path variable in PowerShell to set environment variable for the session or temporary. Use [System. Environment] method in PowerShell to set environment variable permanently.

How do I set the path in PowerShell?

To add to the PATH, append a semicolon and a new path on the end of the long path string. We can use PowerShell to check whether the path we want to add is already in the existing path.

How do I get the PATH environment variable in PowerShell?

Environment variables in PowerShell are stored as PS drive (Env: ). To retrieve all the environment variables stored in the OS you can use the below command. You can also use dir env: command to retrieve all environment variables and values.


Video Answer


1 Answers

You can use Set-Item cmdlet:

$Name,$Value='key1=val1'-split'=',2
Set-Item -LiteralPath Env:$Name -Value $Value

Also you could use [Environment]::SetEnvironmentVariable method:

[Environment]::SetEnvironmentVariable($Name,$Value)

Note, what that only set process environment variables. So, it affects only your process and child processes, started from that point.

like image 73
user4003407 Avatar answered Sep 19 '22 12:09

user4003407