Set environment in current cmd using batch script

8.5k views Asked by At

I did search for an answer before posting this question but I couldn't find anything.

The problem is, I have a CMD shell from which different applications are being launched. What I want is to execute a bat files which can modify the current cmd environment.

In our current setup, we are using call to launch the batch file but that environment doesn't get updated in the callers cmd environment. Is there a command which runs the Batch in the current cmd shell?

1

There are 1 answers

0
DavidPostill On

"The batch file has simple set and setx. When the batch file is executed from the command prompt it opens a new instance and run the bat. So the env changes does not get set on the main cmd."

Both set and setx do not take effect in the command prompt that runs the batch file.

  • set applies to the current command prompt only (this is the new command prompt belonging to the batch file not the one that runs the batch file). These changes are lost when the batch file terminates.

  • setx only affects new command prompts (not those that are already open like the one that is used to run the batch file. You will only see thse changes if you start a completely new command prompt.

What you need to do is have a single batch file that uses set and also launches your applications.

You could start with something like How to Use a Batch File to Create a Command Prompt Menu to Execute Commands and add the appropriate set commands just before you call each application.

ECHO OFF
CLS
:MENU
ECHO.
ECHO ...............................................
ECHO PRESS 1, 2 OR 3 to select your task, or 4 to EXIT.
ECHO ...............................................
ECHO.
ECHO 1 - Open Notepad
ECHO 2 - Open Calculator
ECHO 3 - Open Notepad AND Calculator
ECHO 4 - EXIT
ECHO.
SET /P M=Type 1, 2, 3, or 4 then press ENTER:
IF %M%==1 GOTO NOTE
IF %M%==2 GOTO CALC
IF %M%==3 GOTO BOTH
IF %M%==4 GOTO EOF
:NOTE
cd %windir%\system32\notepad.exe
start notepad.exe
GOTO MENU
:CALC
cd %windir%\system32\calc.exe
start calc.exe
GOTO MENU
:BOTH
cd %windir%\system32\notepad.exe
start notepad.exe
cd %windir%\system32\calc.exe
start calc.exe
GOTO MENU

Source Display, set, or remove CMD environment variables

Permanent changes

Changes made using the SET command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed. To permanently change a variable at the command line use SetX or with the GUI - Control Panel | System | Environment | System/User Variables

Changing a variable permanently with SetX will not affect any CMD prompt that is already open. Only new CMD prompts will get the new setting.