Introduction
Environment variables are dynamic values that the system and scripts use. They store information like paths, usernames, OS settings, and temporary values inside Batch scripts. Mastering them is essential for advanced automation.
1. Viewing All Environment Variables
set
2. Viewing a Specific Variable
echo %USERNAME%
echo %APPDATA%
echo %PATH%
3. Creating Variables (Temporary)
set NAME=Kaloyan
echo %NAME%
4. Variables Inside IF Blocks
set var=10
if %var%==10 (
echo It is 10
)
5. Delayed Variable Expansion
Required when variables change inside loops.
setlocal enabledelayedexpansion
set count=0
for %%i in (*) do (
set /a count+=1
echo File !count!: %%i
)
6. Removing Variables
set NAME=
7. System Environment Variables
Some of the most useful built-ins:
%USERPROFILE%%WINDIR%%TEMP%%CD%(current directory)%DATE%%TIME%
8. PATH Variable
Shows where Windows looks for executables.
echo %PATH%
9. Appending to PATH (Temporary)
set PATH=%PATH%;C:\MyTools\
10. Command Substitution (Storing Command Output)
for /f "delims=" %%a in ('hostname') do set HOST=%%a
echo %HOST%
11. Reading User Input as Variable
set /p NAME=Enter your name:
echo Hello %NAME%
12. Random Number
echo %RANDOM%
13. Environment Variables in Paths
copy file.txt "%APPDATA%\MyApp\"
14. Multi-Line Variables
set TEXT=Line1& echo %TEXT%
15. Exporting Variables to Child Scripts
call child.bat
Child scripts inherit parent variables automatically.
16. Persistently Adding Variables (System-Level)
(Requires admin, using setx)
setx MYVAR "SomeValue"
Note: setx does NOT update current session — only future ones.
Summary
setshows and creates variables!var!is used with delayed expansion%var%is the normal form- Environment variables store system paths, usernames, times, etc.
- Use
for /fto capture command output - Use
setxfor permanent variables