powershellpathenvironment-variableswindows-10

Changing a value in the PATH environment variable


My company uses a program that breaks when Java is updated. This is due to the program install (I assume) placing a static path to Java in the PATH environment variable.

For example, the current PATH variable in question is
C:\Program Files (x86)\Java\jre1.8.0_171\bin\client,

but if Java is updated and the program is re-installed, the PATH variable will update to include C:\Program Files (x86)\Java\jre1.8.0_181\bin\client.

I was able to find exactly what I needed (I think) on Microsoft Dev Blogs, but that code is for Powershell 2.0 and doesn't work on Windows 10.

Is this still possible in Windows 10?


Solution

  • You can use the System.Environment class to modify your environment variables machine-wide:

    # get the PATH and split it up
    $PATH = [Environment]::GetEnvironmentVariable('PATH', 'Machine') -split ';'
    
    # filter out the JRE paths
    $PATH = $PATH -notmatch 'java\\jre'
    # get any real JRE paths
    $PATH += (Get-Item -Path "${Env:ProgramFiles(x86)}\Java\jre*\bin\client").FullName
    $PATH = $PATH -join ';'
    
    [Environment]::SetEnvironmentVariable('PATH', $PATH, 'Machine')
    

    Note: You will need to run your shell elevated to execute these commands.