用bat改变PATH变量?

时间:2014-08-07 12:38:58

标签: windows batch-file cmd

我正在尝试编写2个BATCH工具,这些工具可以改变我的系统变量路径。 第一个应该在路径前面添加一个目的地但是在之前将旧路径保存在txt文件中,并且第二个BATCH文件应该从txt文件加载路径并用保存的路径替换Path以再次恢复旧路径

@echo. 2>%date:~0%_PATH.txt
@echo %PATH% >> %date:~0%_PATH.txt
@echo "This tool will change the system variable PATH"
@echo "if you want to continue, press any key."
@echo "To cancel press CTRL+C"
@pause

@setx /m PATH  "C:\MinGW\bin;%PATH%"
@echo.
@echo.
@echo "The System variables has been set"
@echo "Your original PATH variable was saved to: %date:~0%_PATH.txt"

@pause

这是第一个应该在PATH前面添加C:\ MinGW \ bin的批处理文件。 (在运行批处理文件之后,不仅仅是我的目的地,这不是doint。

@ECHO OFF
ECHO "You are about to restore your system variable PATH to a previous state!"
ECHO "If you want to preform this step, press any key."
ECHO "To cancel the process, press CTRL+C";
ECHO.
SET index=1

SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%f IN (*.*) DO (
   SET file!index!=%%f
   ECHO !index! - %%f
   SET /A index=!index!+1
)

SETLOCAL DISABLEDELAYEDEXPANSION

SET /p selection="Please select by typing the number which file you want to recover      your PATH:"

SET file%selection% > nul 2>&1

IF ERRORLEVEL 1 (
   ECHO Invalid number selected!!  
   EXIT /B 1
)

CALL :RESOLVE %%file%selection%%%
ECHO Selected file name: %file_name%

GOTO :EOF

:RESOLVE
SET file_name=%1
GOTO :EOF

@setx /m PATH %file_name%

这是恢复批处理文件,不会选择我选择的文件。

我希望有人可以帮助我。 谢谢

1 个答案:

答案 0 :(得分:1)

SETX仅更改注册表中的值,而不是当前shell环境中的变量。正如文档所说,当您运行SETX /?时:

NOTE: 1) SETX writes variables to the master environment in the registry.
      2) On a local system, variables created or modified by this tool
         will be available in future command windows but not in the
         current CMD.exe command window.

如果您只想在当前环境中修改PATH的值,只需使用常规SET命令。如果你想两者都做,那么你需要使用这两个命令。