How do I clear all environment variables from a Windows shell session?
Olivia Zamora
If I start a new Windows shell session and type:
envI see lots of environment variables set. I want to debug the running of a command line program by removing all environment variables from the current shell session.
I could go though one by one with the following approach:
SET FOO=
SET BAR=
SET ... ... ...However is there a simple way to clear them all in one go?
13 Answers
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
SetThe 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.
@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