Modifying an Environment Variable remotely with Powershell

15 views Asked by At

I've got an environment variable that is used by multiple applications. For one of those applications, we are starting to use a batch script to set that variable on application startup. I'm trying to get write a powershell script that will only strip out certain parts, almost like the PATH scripts that I've seen elsewhere. Let's say I've got an environment variable named LICENSE_FILE that contains "LicSrv01;LicSrv02;LicSrv03,LicSrv04".

I want to strip out LicSrv01 & LicSrv02, leaving the rest if they exist in that variable. Here is the script that I've tried.

$license = invoke-command -computername $client -Scriptblock {[System.Environment]::GetEnvironmentVariable('LICENSE_FILE','Machine')}

if ($license -ne $NULL) {
    $license = ($license.Split(';') | Where-Object { $_ -ne 'LicSrv01' }) -join ';'
    $license = ($license.Split(';') | Where-Object { $_ -ne 'LicSrv02' }) -join ';'

    invoke-command -computername $client -ScriptBlock { [Environment]::SetEnvironmentVariable('MGLS_LICENSE_FILE',$license,[System.EnvironmentVariableTarget]::Machine) }
}

This works on a local PC, but when I run this on a remote PC the script wipes out the entire environment variable.

0

There are 0 answers