Created
March 29, 2022 20:49
-
-
Save mja00/68379ced8c9ee37f3412bb945cebcecf to your computer and use it in GitHub Desktop.
Powershell Java Swapper
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
# Create a list of java versions to pick from | |
$root_java = "C:\Program Files\Eclipse Adoptium" # This makes it easier to change the location of the java folder | |
$global:java_version_hashtable = [ordered]@{ | |
"8" = "jdk-8.0.312.7-hotspot" | |
"11" = "jdk-11.0.13.8-hotspot" | |
"16" = "jdk-16.0.2+7" | |
"17" = "jdk-17.0.1.12-hotspot" | |
"18" = "jdk-18.0.0.36-hotspot" | |
} | |
# Function that returns the path to the java version | |
# @param java_version - The java version to get the path for | |
# @return - The path to the java version | |
function java_version_path($java_version) { | |
return $root_java + "\" + $java_version | |
} | |
foreach($item in $java_version_hashtable.GetEnumerator()) { | |
# Get the position of the key in the hashtable | |
$index = $($java_version_hashtable.keys).indexOf($item.Key) | |
$java_path = java_version_path($item.Value) | |
$message = "[{2}] Java {0}: {1}" -f $item.Key, $java_path, $($index + 1) | |
Write-Output $message | |
} | |
# Write out the exit message | |
Write-Output "[X] Exit the script" | |
# Prompt the user for input | |
$selected = Read-Host "`nPlease select a java version" | |
# Check if the user selected X to exit | |
if ($selected -eq "X") { | |
exit | |
} | |
if ([int]$selected -gt $java_version_hashtable.count) { | |
Write-Output "[X] Invalid selection" | |
exit | |
} | |
# Get the input'th item from the hashtable | |
$java_version = $($java_version_hashtable.keys)[$selected - 1] | |
$selected_java_path = java_version_path($java_version_hashtable[$java_version]) | |
# Set the JAVA_HOME environment variable | |
$env:JAVA_HOME = $selected_java_path | |
# Reset the PATH variable | |
$env:PATH = "$env:JAVA_HOME\bin;$env:PATH" | |
$message = "`nThe Java version has been set to Java {0}" -f $java_version | |
Write-Output $message |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment