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

Solution 1:

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.

Solution 2:

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.

Solution 3:

@echo off

set var=""

if not exist version1.txt goto END

for /F "delims=" %%a in ('findstr /C:%1 version.txt') do set var=%%a echo %var%

for /f "tokens=1,2,3,4 delims=," %%a in ("%var%") do (

setlocal EnableDelayedExpansion

set first=%%a

set second=%%b

set third=%%c

set fourth=%%d

echo %first% and %second% and %third% and %fourth%

)

goto EXIT :END echo File not found :EXIT