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