Batch Environment Variables

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:

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