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"
}
}
$MyEnvVaris evaluated in the context of the remote machine rather than your local value. Use$using:MyEnvVarto remote it.