Last active
March 26, 2025 08:50
-
-
Save holmeszyx/b60e34d7264dccb7f95eba11c72ab45c to your computer and use it in GitHub Desktop.
Swith java version in PowerShell. Saving the script and Appending '. "C:\Path\To\Your\Script\switch-java.ps1"' to "$PROFILE" file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Switch-Java { | |
param ( | |
[string]$Version | |
) | |
# The location of multi-version java | |
$javaPaths = @{ | |
"8" = "C:\Programs\dev\java\java" | |
"11" = "C:\Programs\dev\java\java11" | |
"17" = "C:\Programs\dev\java\java17" | |
} | |
# check input | |
if (-not $javaPaths.ContainsKey($Version)) { | |
Write-Host "Invalid Java version. Available versions: 8, 11, 17" | |
return | |
} | |
# new java home | |
$javaHome = $javaPaths[$Version] | |
# set java home | |
[System.Environment]::SetEnvironmentVariable("JAVA_HOME", $javaHome, [System.EnvironmentVariableTarget]::Process) | |
# old path | |
$currentPath = [System.Environment]::GetEnvironmentVariable("PATH", [System.EnvironmentVariableTarget]::Process) | |
# remove outdated java path | |
$newPath = ($currentPath -split ';' | Where-Object { | |
$javaPaths.Values -notcontains $_ -and $javaPaths.Values -notcontains ($_ -replace '\\bin$', '') | |
}) -join ';' | |
# new path | |
$newPath = "$javaHome\bin;$newPath" | |
[System.Environment]::SetEnvironmentVariable("PATH", $newPath, [System.EnvironmentVariableTarget]::Process) | |
# classpath | |
$classPath = ".;$($javaHome)\lib" | |
[System.Environment]::SetEnvironmentVariable("CLASSPATH", $classPath, [System.EnvironmentVariableTarget]::Process) | |
# print result JAVA_HOME\PATH\CLASSPATH | |
Write-Host "JAVA_HOME set to: $javaHome" | |
Write-Host "PATH updated to include: $javaHome\bin" | |
Write-Host "CLASSPATH set to: $classPath" | |
Write-Host "" | |
# java now | |
java -version | |
} | |
# alias | |
Set-Alias -Name sj -Value Switch-Java |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment