Persistently set environment variables on Windows
Set a user or machine environment variable for good — the three scopes ($env:, User, Machine) explained, and why setx truncates.
01Command
$ [Environment]::SetEnvironmentVariable('JAVA_HOME', 'C:\Program Files\Java\jdk-21', 'User')02What it does
$env:JAVA_HOME = '...' only lasts for that PowerShell session; SetEnvironmentVariable with a Target writes to the registry so every future process inherits it. A deliberate quirk: the current session still won't see it — also set $env:JAVA_HOME in the same script if you need it immediately. In CMD the equivalent is `setx JAVA_HOME "..."`, which persists too but silently truncates values over 1024 characters — a famous trap when editing PATH this way.
03Risk
04Undo
$ [Environment]::SetEnvironmentVariable('JAVA_HOME', $null, 'User')05Sources
- Environment.SetEnvironmentVariable Method | Microsoft LearnEvidence: Microsoft documents SetEnvironmentVariable(name, value, EnvironmentVariableTarget) where Machine/User persist to the registry and passing null deletes the variable.
- SETX - Windows CMDEvidence: SS64 documents setx persisting environment variables to the registry for future sessions, without affecting the current one.
Last verified: 2026-09-17 · Category: Developer
06Related solutions
Use Windows Package Manager to install, search, and upgrade thousands of applications from the community repository in one command.
Understand PowerShell's execution policy scopes and set the one that lets you run your own local scripts without gutting the security model.
Search inside text files and logs with regex, returning file, line number and match.