Skip to content

Instantly share code, notes, and snippets.

Last active June 30, 2018 21:04
What would you like to do?
Set system environment variables for Java development in Windows.
Set system environment variables for JAVA development.
The JDK architecture. e.g., x64, x86 (32 bit)
The name of the folder where the JDK is installed, e.g., jdk1.8.0_172
./java.ps1 -a x64 -n jdk1.8.0_172
Author: Jim Frenette
Date: June 30, 2018
# since we're setting machine level environment variables using .NET framework integration
# an elevated PowerShell prompt as the Administrator Role is required
function CheckForElevatedSession
# 1. find out who the user is
$WindowsIdentity = [System.Security.Principal.Windowsidentity]::GetCurrent()
# 2. instantiate a new Windows Security Principal object using the $WindowsIdentity as its argument.
# this object is necessary because it exposes the IsInRole method.
$Principal = New-Object System.Security.Principal.WindowsPrincipal($WindowsIdentity)
$AdminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
if ($Principal.IsInRole($AdminRole)) {
Write-Host -ForegroundColor Green "Elevated PowerShell session detected. Continuing."
} else {
Write-Host -ForegroundColor Red "This script must be run in an elevated PowerShell window. Please launch an elevated session and try again."
function SetJavaEnv
# Param needs to be at the top if not in a function
HelpMessage="Enter the architecture, e.g., x64 or x86 (32 bit)")]
HelpMessage="Enter the name of the folder where the JDK is installed, e.g., jdk1.8.0_172 or jdk-10.0.1")]
) #end param
# set javapath var
switch ($Arch.ToLower())
"x64" {
$JavaPath = $Env:ProgramFiles + "\Java"
"x86" {
$JavaPath = ${Env:ProgramFiles(x86)} + "\Java"
default {
Write-Host -ForegroundColor Red "invalid architecture parameter:" $Arch
Write-Host -ForegroundColor Red "must be either x64 or x86"
if ( Test-Path -Path $JavaPath\$Name ) {
$Confirm = Read-Host "Set JAVA_HOME = "$JavaPath\$Name "? [y/n]"
if ($Confirm.ToLower() -eq 'n') { exit }
# set machine level environment variable using .NET framework integration
[Environment]::SetEnvironmentVariable("JAVA_HOME", $JavaPath + "\" + $Name, "Machine")
$JavaBin = $JavaPath + "\" + $Name + "\bin"
$Confirm = Read-Host "ADD" $JavaBin "TO PATH ? [y/n]"
if ($Confirm.ToLower() -eq 'n') { exit }
# get the current PATH from the environment keys in the registry
$ExistingPath = [System.Environment]::GetEnvironmentVariable("path")
# update the path
$PathArray = $ExistingPath -split ';'
if ($PathArray -notcontains $JavaBin) {
$PathArray = $PathArray + $JavaBin | Where-Object { $_ }
$Path = $PathArray -join ';'
# update the path
# $Path = $ExistingPath + ";" + $JavaBin
[System.Environment]::SetEnvironmentVariable("path", $Path, "Machine")
} else {
Write-Host -ForegroundColor Red "JDK Path:" $JAVAPATH\$name " does not exist"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment