5

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

2 Answers 2

7

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.

0
1

You can also use the Set-Variable command in PowerShell:

Set-Variable -Name "..." -Value "..."

Then you can use a couple of commands to check that the variable was set properly: echo, Write-Host, Get-Variable :

  1. echo $...
  2. Write-Host "$..."
  3. Get-Variable -Name "..."

Example 1:

Set-Variable -Name "Employee" -Value "John"

echo $Employee 

Example 2:

Set-Variable -Name "Employee" -Value "John"

Write-Host "$Employee" 

Example 3:

Set-Variable -Name "Employee" -Value "John" 

Get-Variable -Name "Employee"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.