Search code examples
javapowershellvariablesenvironment

Modify part of the JAVA_HOME folder path using powershell


I have an application that wants the Windows JAVA_HOME variable not to contain spaces.
I would like an efficient PS script to get the current folder path i.e.
"C:\program files\java\java.versionxxxx", convert only "program files" to "progra~1" and update the environment variable accordingly.


Solution

  • This should do the trick

    $newPath = $ENV:JAVA_HOME.replace('Program Files','Progra~1')
    
    [System.Environment]::SetEnvironmentVariable("JAVA_HOME", "$NewPath", [System.EnvironmentVariableTarget]::Machine)
    

    You need local administrator access to modify Machine environment variable. Change ::machine into ::user if the change is for a specific user profile