Crude but effective functions I use to manually manage JAVA_HOME on Windows using Powershell 7+, for those times where a project can only use a certain LTS version.
Placed in the Powershell profile file, it just attempts to find the latest version of the specific version and updates your JAVA_HOME evironment varaible.
If your path setup also relies on JAVA_HOME to add Java commands to the path, this also updates those after a refreshenv.
function jdkFinder($version) {
$env:JAVA_HOME=$(
Get-ChildItem -Path "$HOME\.jdks","C:\Program Files\Amazon Corretto" -Attributes "Directory"
| Where-Object -Property Name -Match $version
| Add-Member -PassThru -MemberType ScriptProperty -Name "Version" -Value {
$this.Name.Replace("jdk","").Replace("corretto-","")
}
| Sort-Object -Property Version -Descending
| Select-Object -First 1
).FullName
# Persist the change
[Environment]::SetEnvironmentVariable("JAVA_HOME", $env:JAVA_HOME, [EnvironmentVariableTarget]::User)
Write-Host "`nSet JAVA_HOME to ${env:JAVA_HOME}`n"
}function java25 {
jdkFinder 25
}C:\> java25
Set JAVA_HOME to C:\Users\Beer\.jdks\corretto-25.0.2