TExcelTAD
Home › Windows CMD & Batch › Environment Variables & PATH

Environment Variables & PATH

Every program on Windows starts with a small dictionary of environment variables: name/value pairs such as USERNAME=ada or TEMP=C:\Users\ada\AppData\Local\Temp. Command Prompt reads them with %NAME%, batch files use them to find folders without hard-coding paths, and one of them, PATH, decides which program runs when you type a bare command name.

You already used variables in Batch Variables. This lesson is about the ones Windows gives you, how long a change lasts, and how PATH works.

Where the values come from

When you log in, Windows builds the environment from three places and hands a copy to every process you start:

text
 System variables  (HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment)
        +
 User variables    (HKCU\Environment)            user PATH is APPENDED to system PATH
        +
 Dynamic values    (USERNAME, COMPUTERNAME, USERPROFILE, ...)
        |
        v
 explorer.exe ---> cmd.exe ---> your batch file ---> programs it starts
                 (each child gets a COPY of its parent's environment)

The last line is the key rule: a child gets a copy. A change made inside cmd.exe is visible to that window and to the programs it starts, but never flows back to the parent or sideways to other windows.

Reading variables

cmd · try it yourself
@echo off
echo User:      %USERNAME%
echo Computer:  %COMPUTERNAME%
echo Profile:   %USERPROFILE%
echo OS family: %OS%
echo CPU arch:  %PROCESSOR_ARCHITECTURE%
User:      learner
Computer:  TAD
Profile:   C:\Users\learner
OS family: Windows_NT
CPU arch:  AMD64

The playground runs as user learner on a computer called TAD; on your PC you'll see your own names. Names are case-insensitive: %username% and %USERNAME% are the same variable.

The most useful built-in variables:

Variable Typical value on Windows 11 Use it for
USERPROFILE C:\Users\ada the user's home folder
APPDATA / LOCALAPPDATA C:\Users\ada\AppData\Roaming / ...\Local per-user settings and caches
TEMP / TMP C:\Users\ada\AppData\Local\Temp scratch files
SystemRoot / windir C:\Windows the Windows folder
ProgramFiles / ProgramFiles(x86) C:\Program Files / C:\Program Files (x86) installed programs
ComSpec C:\Windows\system32\cmd.exe path of the command interpreter
PATHEXT .COM;.EXE;.BAT;.CMD;.VBS;... extensions tried when you omit one
CD, ERRORLEVEL, RANDOM, DATE, TIME (computed on every read) "dynamic" variables, not stored anywhere

Typing set alone lists the whole environment; set PRO lists every variable whose name starts with PRO:

cmd · try it yourself
@echo off
set USER
USERDOMAIN=TAD
USERNAME=learner
USERPROFILE=C:\Users\learner

set: changes for this window only

set NAME=value creates or changes a variable in the current cmd.exe process. set NAME= (nothing after =) deletes it, and if defined NAME tests whether it exists. Inside a batch file, wrap changes in setlocal … endlocal so they disappear when the script ends instead of leaking into the caller's window (see setlocal & Delayed Expansion):

cmd · try it yourself
@echo off
set "BUILD_MODE=debug"
setlocal
set "BUILD_MODE=release"
set "API_KEY=abc123"
echo inside:  BUILD_MODE=%BUILD_MODE%
endlocal
echo outside: BUILD_MODE=%BUILD_MODE%
if defined API_KEY (echo API_KEY survived) else (echo API_KEY is gone)
set "BUILD_MODE="
if not defined BUILD_MODE echo BUILD_MODE deleted
inside:  BUILD_MODE=release
outside: BUILD_MODE=debug
API_KEY is gone
BUILD_MODE deleted

A common pattern is a default value: use the variable if the caller set it, otherwise fall back:

cmd · try it yourself
@echo off
if not defined OUTPUT_DIR set "OUTPUT_DIR=%USERPROFILE%\out"
echo Writing to %OUTPUT_DIR%
set "OUTPUT_DIR=D:\builds"
call :show
goto :eof
:show
echo A called label sees the same environment: %OUTPUT_DIR%
Writing to C:\Users\learner\out
A called label sees the same environment: D:\builds

setx: permanent changes

setx writes a variable into the registry, so it survives reboots and appears in every new window. It has three surprises:

  1. It does not change the current window. Run set as well if you need the value right now.
  2. The syntax has no =: setx NAME "value".
  3. /M writes a system variable (needs an elevated prompt); without it you write a user variable.
cmd
C:\Users\ada>setx EDITOR "code --wait"

SUCCESS: Specified value was saved.

C:\Users\ada>echo %EDITOR%
%EDITOR%

C:\Users\ada>setx /M JAVA_HOME "C:\Program Files\Java\jdk-21"
ERROR: Access to the registry path is denied.

Sample session: the echo still prints %EDITOR% literally (an undefined variable is not expanded on the command line) until you open a new window. The /M call failed because the prompt wasn't elevated. To delete a permanent variable, use Settings → System → About → Advanced system settings → Environment Variables, or reg delete HKCU\Environment /v EDITOR /f (see reg: The Registry).

Warning: never run setx PATH "%PATH%;C:\Tools". %PATH% in your window is the merged system + user path, so you would copy the whole system path into your user path, and older setx versions silently truncate values at 1024 characters. Edit PATH in the Environment Variables dialog instead, or with PowerShell's [Environment]::SetEnvironmentVariable('Path', ..., 'User').

PATH: how commands are found

When you type git (no folder, no extension), cmd searches:

  1. built-in commands (dir, set, echo, …),
  2. the current folder,
  3. each folder of PATH, left to right,

and in each folder it tries every extension of PATHEXT in order (git.com, git.exe, git.bat, …). The first match wins; if nothing matches you get 'git' is not recognized as an internal or external command, operable program or batch file.

PATH is a single string with ; between folders. Batch can split it with a substitution trick: replace every ; with " " and wrap the whole thing in quotes, which turns it into a list of quoted items for for:

cmd · try it yourself
@echo off
setlocal
set "PATH=C:\Program Files\Git\cmd;C:\Tools;C:\Users\ada\bin"
set /a n=0
for %%p in ("%PATH:;=" "%") do (
  set /a n+=1
  call echo %%n%%. %%~p
)
1. C:\Program Files\Git\cmd
2. C:\Tools
3. C:\Users\ada\bin

%%~p strips the quotes again. (call echo %%n%% re-reads n on every pass; delayed expansion with !n! works too.)

Order matters. Here two folders both contain a hello.bat, and whichever folder comes first in PATH wins. The %%~$PATH:i modifier performs the same search and prints the full path of the match, which is how you answer "which hello would run?":

cmd · try it yourself
@echo off
setlocal
mkdir tools-old tools-new
>tools-old\hello.bat echo @echo hello from tools-old
>tools-new\hello.bat echo @echo hello from tools-new
set "PATH=%CD%\tools-new;%CD%\tools-old;%PATH%"
call hello
for %%i in (hello.bat) do echo resolved to: %%~$PATH:i
set "PATH=%CD%\tools-old;%PATH%"
call hello
for %%i in (missing.exe) do echo missing.exe: [%%~$PATH:i]
hello from tools-new
resolved to: C:\Users\learner\tools-new\hello.bat
hello from tools-old
missing.exe: []

Prepending to PATH (set "PATH=C:\new;%PATH%") lets your folder win; appending lets the existing ones win. Inside setlocal the change is gone when the script ends, which is exactly what you want for a build script.

On a real machine, where searches the current folder and PATH and lists every match, in search order:

cmd
C:\Users\ada>where python
C:\Users\ada\AppData\Local\Programs\Python\Python313\python.exe
C:\Users\ada\AppData\Local\Microsoft\WindowsApps\python.exe

C:\Users\ada>where nothing
INFO: Could not find files for the given pattern(s).

Sample output. The second python.exe is the Microsoft Store "app execution alias"; because the real install comes first in PATH, it wins.

PowerShell equivalents

CMD PowerShell
echo %USERNAME% $env:USERNAME
set USER Get-ChildItem env:USER*
set "X=1" $env:X = '1'
set "X=" Remove-Item env:X
setx X 1 [Environment]::SetEnvironmentVariable('X', '1', 'User')
where git Get-Command git -All

More in PowerShell Environment Variables; the Linux side is in Bash Environment.

Test yourself

You run setx COLOR blue and then echo %COLOR% in the same window. What is printed?

  1. blue
  2. %COLOR% (or the old value), because setx doesn't change the current window
  3. An error: setx needs an = sign
  4. Nothing until you reboot

PATH is C:\A;C:\B and both folders contain tool.exe. Which runs when you type tool?

  1. C:\B\tool.exe, the last one wins
  2. C:\A\tool.exe, folders are searched left to right
  3. Both, one after the other
  4. cmd asks which one to use

What does set "TOKEN=" do?

  1. Sets TOKEN to an empty string that if defined still finds
  2. Deletes the variable TOKEN
  3. Prints the value of TOKEN
  4. Sets TOKEN to two quote characters