'IntelliJ powershell terminal prepend PATH

On my system, I have multiple Java versions installed due to having many projects with different requirements. Managing the Java versions in IntelliJ on per-project level works like a charm except for the IntelliJ integrated terminal. By default, the terminal is executed as is, i.e. with the system java settings, not with the project java settings.

Therefore, for the terminal, I want to overwrite JAVA_HOME and prepend the path with $JAVA_HOME/bin. Instead of doing this manually everytime I open the terminal, I thought of setting this per project so that when opening the terminal in the project, java works correctly.

I found File -> settings -> Tools -> Terminal and came up with different ideas in that dialog which turned out to not work as I expected them to:

  1. I changed the environment variables in the Environmental variables dialog. This worked well for JAVA_HOME but not so well for the Path: I only saw the option to replace the entire Path, but not to prepend it! From time to time, I install new tools on my machine which shall be on the path for all terminals, so this solution seems to no be ideal.
  2. Inspired by another post on StackOverflow for cmd (I want to execute Powershell), I tried to change the Shell path and populate my environment as a program argument ( PyCharm Windows: how to modify the shell PATH of the command line? )
    1. My first try was powershell.exe -NoExit -command '$env:JAVA_HOME=''C:\PROGRA~1\Java\jdk-13.0.1''; $env:Path = $env:JAVA_HOME + ''\bin;'' + $env:Path'. This worked well from within an existing powershell: change path with powershell in powershell variant 1 but did not work with IntelliJ dialog: intellij shell path variant 1 intellij terminal variant 1
    2. I then came up with the idea to change the environment via another method in powershell "per process". Again, this also worked on a powershell-2-powershell test, but not intellij-2-powershell: powershell.exe -NoExit -command '& {[Environment]::SetEnvironmentVariable(''JAVA_HOME'',''C:\PROGRA~1\Java\jdk-13.0.1'',''Process''); [Environment]::SetEnvironmentVariable(''Path'',$env:JAVA_HOME + ''\bin;'' + $env:Path,''Process'')}'change path with powershell in powershell variant 2 and again did not work in IntelliJ: shell path variant 2 intellij terminal variant 2

My question(s)

  • Do you know a solution on how I can prepend the PATH with my custom JAVA_HOME for powershell terminal within IntelliJ?
  • Do you know why powershell behaves differently here vs. powershell in powershell? My guess would be that IntelliJ somehow forks the process twice, maybe when injecting their own environment modifications or something like this?


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source