Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing environment variables to a process in PowerShell 2.0 when the variable is changed multiple times

I'm having some issue when it comes to passing the corresponding environment variables to a process. Below you can see part of my code so that you can understand what I'm trying to do.

I have two EXE files that I need to run. The processes run some updates based on the location of the Environment variable %MainFiles%. When I run the code it seems the EXE files do not recognize the change. However, when i look under the Computer properties I do see that the variables are changed correctly.

Does anyone know how could I force the process to recognize the change? Thanks

while ($i -lt $Size) {
  if ($TempEnv[$i] -eq "Done"){
    $ExitCode="Completed"
    return
  } else {
    $Temp = $TempEnv[$i]
    Write-Host ("Starting Update for  " + $Temp) -foregroundcolor "Green"

    [System.Environment]::SetEnvironmentVariable("MainFiles", "$Temp","Machine")
    [System.Environment]::GetEnvironmentVariable("MainFiles","Machine")
    Copy-Item $CopyInstallData -destination $Temp
    $process = Start-Process XMLUpgrade.exe -WorkingDirectory "C:\Program Files\Dtm" -wait
    $process = Start-Process Update.exe -WorkingDirectory "C:\Program Files\Dtm" -wait
.
.
.
like image 555
RHQ Avatar asked Oct 04 '22 08:10

RHQ


1 Answers

This line makes the env var change permanent:

[System.Environment]::SetEnvironmentVariable("MainFiles", "$Temp","Machine")

Unfortunately PowerShell has already launched before you set this. Its env block is snapshotted at launch time. That environment is what the two spawned processes inherit.

To get the two processes to launch with the correct environment variable value do this first:

$env:MainFiles = $Temp
like image 140
Keith Hill Avatar answered Oct 10 '22 03:10

Keith Hill