How to Set Environment Variables Using Batch Files

April 6, 2025

Batch files can be used to set environment variables, making them useful for configuring system settings, paths, and other variables dynamically.

Set a Temporary Environment Variable

A temporary environment variable is available only for the duration of the command prompt session. Once the terminal is closed, the variable is lost.

@echo off
set MY_VARIABLE=HelloWorld
echo %MY_VARIABLE%
pause

Set a Permanent Environment Variable

To set an environment variable permanently, use the setx command. This ensures the variable remains even after restarting the system.

@echo off
setx MY_VARIABLE "HelloWorld"
echo Environment variable set successfully.
pause

Set a System-Wide Environment Variable

To set an environment variable for all users, run the script as an administrator.

@echo off
setx MY_VARIABLE "HelloWorld" /M
echo System-wide variable set successfully.
pause

Delete an Environment Variable

To remove a temporary environment variable, use:

set MY_VARIABLE=

To remove a permanent environment variable, use:

REG delete "HKCUEnvironment" /F /V MY_VARIABLE

For system-wide removal, use:

REG delete "HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment" /F /V MY_VARIABLE

Final Thoughts

Using batch scripts to manage environment variables simplifies system configurations. Whether setting variables temporarily or permanently, this method helps automate system setup efficiently.