If I start a new Windows shell session and type:

env

I 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?

link|improve this question
What is env? I've never heard of that before, and it does not work here. – paradroid Dec 5 '11 at 12:44
feedback

1 Answer

up vote 4 down vote accepted

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.

link|improve this answer
This is great. Thanks! One small thing: the backupenv.bat file seems to have 2 trailing spaces at the end of every SET A=B line. This seems to screw up some variables on restoring. – TiGz May 4 '11 at 15:58
Removed the space following %%a=%%b, see the edited answer. Should be fine now. – Gareth May 4 '11 at 16:04
That got rid of one of the two spaces... one space remains at the end of each SET line. Which is weird. – TiGz May 4 '11 at 16:13
Perhaps the space was added from when you previously ran my (slightly broken) script, and you ran the batch to restore... thus adding a space to each variable? Then you ran it again and in the output it would have two spaces? If this is the case then sorry for previously having suffixed all your variables with a space. Should be easy to clean up though. – Gareth May 5 '11 at 0:54
Nah - I was opening a new shell each time. Try it... do you not end up with an extra space? – TiGz May 5 '11 at 9:25
show 1 more comment
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.