How do I clear all environment variables from a Windows shell session?

You can write this in a batch file:

@echo off
if exist ".\backupenv.bat" del ".\backupenv.bat"
for /f "tokens=1* delims==" %%a in ('set') do (
echo set %%a=%%b>> .\backupenv.bat
set %%a=
)

It basically runs through each environment variable, backs them up to a batch file (backupenv.bat) and then clears each variable. To restore them you can run the backupenv.bat file.


If you only want to clear all environment variables for the batch file, it gets even easier.

@echo off
Setlocal enabledelayedexpansion
Set >set

For /F "tokens=1* delims==" %%i in (set) do set %% %i=
Del set
Set

The final line outputs all the environment variables, which should be none, confirming the code worked.

Because Setlocal is used, all environment changes are lost after the batch ends. So if you type Set after the batch, you'll see all the environment variables are still there hence no need to store it in a backup file.

Tags:

Windows

Shell