Page 1 of 1
How to clear global variables when launching cmd from within a batch?
Posted: 14 Jun 2022 17:42
by vin97
What is the syntax for the start command to launch cmd.exe in a way where only specific variables are retained?
Example:
Code: Select all
set "VariableThatsSupposedToBePassedOn=X"
set "VariableThatsNotSupposedToBePassedOn=Y"
start "" cmd.exe "set "var=%VariableThatsSupposedToBePassedon%" & echo "%var%" & echo "%VariableThatsNotSupposedToBePassedOn%""
Result I want from the second cmd instance:
Re: How to clear global variables when launching cmd from within a batch?
Posted: 14 Jun 2022 18:14
by ShadowThief
All child instances inherit the environment of their parents. If you don't want a variable to exist inside of a child instance, you'll have to unset the variable before you spawn the child process.
Re: How to clear global variables when launching cmd from within a batch?
Posted: 14 Jun 2022 18:55
by vin97
Is there no way to spawn a completely fresh cmd instance?
I wouldn't have a problem utilizing temp files to pass on the few select variables that have to be kept.
Re: How to clear global variables when launching cmd from within a batch?
Posted: 15 Jun 2022 01:02
by aGerman
START /I will spawn a process that inherits only from explorer.
caller.bat
Code: Select all
@echo off
set "foo=bar"
start "without /I" cmd /k "new.bat"
start "with /I" /I cmd /k "new.bat"
new.bat
Steffen
Re: How to clear global variables when launching cmd from within a batch?
Posted: 15 Jun 2022 03:20
by vin97
Thanks. Was looking in the wrong place (cmd switches).
Re: How to clear global variables when launching cmd from within a batch?
Posted: 15 Jun 2022 09:42
by aGerman
Haha, don't worry. The description for option /I is confunsing anyway (and the German help text is even completely meaningless here
).
Steffen
Re: How to clear global variables when launching cmd from within a batch?
Posted: 15 Jun 2022 11:06
by Aacini
You may use this method in any batch file:
Code: Select all
@echo off
setlocal
rem Remove all environment variables
rem but preserve certain ones
(
for /F "delims==" %%v in ('set') do set "%%v="
set "comspec=%comspec%"
set "path=%path%"
set "VariableThatsSupposedToBePassedOn=%VariableThatsSupposedToBePassedOn%"
)
Antonio