正确配置JDK环境变量后仍找不到Java命令 [英] Java command still not found after configuring JDK environment variable correctly

查看:921
本文介绍了正确配置JDK环境变量后仍找不到Java命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的事情是在Windows虚拟机启动时安装JDK,使用cloudinit用户数据将PowerShell脚本传输到Windows计算机,然后运行该脚本来安装JDK.

I do a thing to install JDK when a Windows virtual machine boot, use a cloudinit user-data to transfer a PowerShell script to the windows machine, and run the script to install JDK.

$softwares = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*
$jdk = $softwares | Where-Object DisplayName -match 'Java SE Development Kit'
$java_home = $jdk.InstallLocation.Trim('\')
#$java_home = "C:\Program Files\Java\jdk1.7.0_80"
$classpath = ".;%JAVA_HOME%\lib;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar"
$path = ";%JAVA_HOME%\bin;" + $env:Path
[Environment]::SetEnvironmentVariable("JAVA_HOME", $java_home, "machine")
[Environment]::SetEnvironmentVariable("CLASSPATH", $classpath, "machine")
[Environment]::SetEnvironmentVariable("PATH", $path , "machine")

问题是我的脚本成功安装了JDK并正确修改了环境变量,但是命令java仍然无法运行.路径正确,注册表中的路径也正确.

The problem is my script installs the JDK successfully and modifies the environment variables correctly, but the command java still doesn't run. The path is right and the path in the registry is right,too.

我确定路径是正确的,因为当我通过My​​PC/RigthClick/Properties/Advaced/EnvironmentVariables/之类的步骤修改"Path"(在"Path"的开头删除',')时,该路径是正确的.而且我还尝试配置不带;"的路径"在头部,仍然无法成功运行java,通过添加;"修改"Path",它运行良好.

I am sure the path is right because when I modify "Path" (delete ',' in the head of "Path") by steps such as MyPC/RigthClick/Properties/Advaced/EnvironmentVariables/. And I also try to configure "Path" without ";" in the head, still can't run java successfully, modify "Path" by add ";", it runs well.

推荐答案

环境变量存储在注册表中. [Environment]::SetEnvironmentVariable()将给定变量写为REG_SZ值,但是要扩展嵌套变量,则需要REG_EXPAND_SZ值.

Environment variables are stored in the registry. [Environment]::SetEnvironmentVariable() writes the given variable as a REG_SZ value, but for nested variables to be expanded you need a REG_EXPAND_SZ value.

如果要在PATH中使用%JAVA_HOME%\bin,请使用Set-ItemProperty而不是[Environment]::SetEnvironmentVariable():

If you want to use %JAVA_HOME%\bin in the PATH use Set-ItemProperty instead of [Environment]::SetEnvironmentVariable():

$regkey = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
Set-ItemProperty -Path $regkey -Name 'Path' -Value $path -Type ExpandString

请注意,由于嵌套变量的扩展顺序,在环境变量中使用嵌套变量时可能还会有其他陷阱. Raymond Chen在文章 Windows机密:隐藏的变量中描述了这种行为.

Beware that there may be other pitfalls when using nested variables in environment variables due to the order in which they're expanded. Raymond Chen described the behavior in the article Windows Confidential: The hidden variables.

这篇关于正确配置JDK环境变量后仍找不到Java命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆