0

Good-day all,

I've written a PowerShell function to help me update a System Environment Variable on a bunch of Windows 7 and 10 Enterprise machines. I've noticed, however, that my "[System.Environment]::SetEnvironmentVariable()" command is deleting the existing variable and not changing its value - like I'm expecting it to.

What am I doing wrong?

Here's a snippet of the relevant code:

$ComputerName = "SERVER1"
$MyEnvVar = "C:\Some_Path\"

ForEach ($Computer in $ComputerName){

    $Online = Test-Connection -ComputerName $Computer -Count 2 -Quiet

    If ($Online -eq $True){
        $OldValue = Invoke-Command $Computer -ScriptBlock {[System.Environment]::GetEnvironmentVariable("MyVariableName","Machine")}
        Write-Host "Old Value is: $OldValue"
        Invoke-Command $Computer -ScriptBlock {[System.Environment]::SetEnvironmentVariable("MyVariable","$MyEnvVar","Machine")}
        $NewValue = Invoke-Command $Computer -ScriptBlock {[System.Environment]::GetEnvironmentVariable("MyVariableName","Machine")}
        Write-Host "New Value is: $NewValue"

    }
}
2
  • $MyEnvVar is evaluated in the context of the remote machine rather than your local value. Use $using:MyEnvVar to remote it. Commented May 15, 2019 at 14:45
  • Do I do that when I'm declaring $MyEnvVar or when I'm using it in the Set command? Commented May 15, 2019 at 14:57

1 Answer 1

2

Change this line:

  Invoke-Command $Computer -ScriptBlock {[System.Environment]::SetEnvironmentVariable("MyVariable","$MyEnvVar","Machine")}

to:

 Invoke-Command $Computer -ScriptBlock {[System.Environment]::SetEnvironmentVariable("MyVariable",$Using:MyEnvVar,"Machine")}

From about_scopes:

Example 5: Using a Local Variable in a Remote Command

For variables in a remote command created in the local session, use the Using scope modifier. PowerShell assumes that the variables in remote commands were created in the remote session.

Also checkout about_remote_variable.

Sign up to request clarification or add additional context in comments.

1 Comment

That worked like a charm and I've learned something new in the process, thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.