Windows CMD 将 PATH 变量重置为默认值

Windows CMD 将 PATH 变量重置为默认值

我有一个问题,肯定有人遇到过,但也许我没有使用正确的搜索词。我希望将命令提示符中的 PATH 变量重置为默认值。因此,例如,我打开一个提示

set PATH=C:\someting\bin;%PATH%
REM do something
set PATH=<original when window was opened>
REM do something else

我看到两种解决方案:

1. 笨拙

set ORIPATH=%PATH%
set PATH=C:\someting\bin;%PATH%
REM do something
set PATH=%ORIPATH%
REM do something else

2. 单独的命令

cmd.exe /k
set PATH=C:\someting\bin;%PATH%
REM do something
exit
cmd.exe/k
set PATH=C:\someting_else\bin;%PATH%
REM do something else
exit

这似乎有一个明显的缺点,即其他环境设置会丢失。

有没有更好的方法?如果有,是什么?

提前致谢!

答案1

Windows 中命令提示符的最新版本允许您维护具有有限范围的环境的本地副本;范围使用SETLOCALENDLOCAL命令表示。通过用这些命令将批处理文件中的代码块括起来,您可以确保您对环境所做的任何更改(除非您使用SET /M)都将是非持久的,并且在退出范围时将恢复:

SET FOO=BAR
...do stuff...
ECHO %FOO%
REM FOO still equals BAR unless stuff changed it
SETLOCAL
...do more stuff...
ECHO %FOO%
REM FOO still equals BAR unless more stuff changed it
SET FOO=QUUX
... do still more stuff...
ECHO %FOO%
REM FOO still equals QUUX unless still more stuff changed it
ENDLOCAL
ECHO %FOO%
REM FOO is back to equalling BAR, or whatever stuff changed it to

相关内容