I created a bat file to setup my workspace by changing the directory to the workspace directory and calling the setupEnv.bat file. But while I'm executing the below bat file in PowerShell, the instructions after cmd are not executing. I need to call the setupEnv.bat file in cmd. If I remove the cmd it will work fine. But I want call the setupEnv.bat on cmd not in PowerShell.
D:
cd D:\WorkSpace\
cmd
call setupEnv.bat
echo "Setup Completed"
- After calling the setupEnv.bat and calling cmd, will it keep all the environment variable setup in the PowerShell ?
This article addresses your exact scenario:
Windows IT Pro - Take Charge of Environment Variables in PowerShell
The reason the variables disappear is that a
.bat
or.cmd
runs in a separatecmd.exe
process (when the process terminates, you lose the variables).The article presents a PowerShell function you can use to run a
.bat
or.cmd
script and retain the environment variables it sets:The article also has a couple of functions for setting and restoring environment variable values in PowerShell.
try Something like this into your PowerShell script:
After calling the setupEnv.bat and calling cmd, will it keep all the environment variable setup in the PowerShell?
No. Any legacy commands invoked from PowerShell will run in a separate (child) process.
Proof:
Add above line to your batch-file, e.g. to
setupEnv.bat
and call it from powershellD:\bat\setupEnv.bat
,&
call operator& D:\bat\setupEnv.bat
,.
dot sourced& D:\bat\setupEnv.bat
,cmd
ascmd /D /C D:\bat\setupEnv.bat
, or& cmd /D /C D:\bat\setupEnv.bat
, or. cmd /D /C D:\bat\setupEnv.bat
.Result is always the same or at least very alike:
Paraphrased from this Foredecker's answer to similar question:
Solution: call Powershell from
cmd
/batch script rather than vice versa