Add/Remove from Path using Batch?

2019-09-02 03:01发布

I want to have two batch files install.bat and uninstall.bat that are in the same folder as my command-line program program.exe.

I want the install.bat to add the current location of program.exe to the System Path environment variable.

Then I want the uninstall.bat to remove any paths to program.exe from the System Path environment variable.

Any ideas on how to do this?

1条回答
闹够了就滚
2楼-- · 2019-09-02 04:00

Perhaps This earlier solution would be of assistance.

A modified file to custom-fit your situation would be

@ECHO OFF
SETLOCAL
SET "batchdir=%~dp0"
SET "batchdir=%batchdir:~0,-1%"
SET "newpath="
:temploop
SET tempfile=%random%%random%%random%
IF EXIST "%temp%\%tempfile%*" GOTO temploop
SET "tempfile=%temp%\%tempfile%"
CALL :showpath >"%tempfile%"
:: This part removes the current directory from the path
FOR /f "delims=" %%p IN ('type "%tempfile%"') DO (
 CALL :addsegment "%%p"
)
DEL "%tempfile%"
IF /i "%1"=="/u" (SET "newpath=%newpath:~1%") ELSE (SET "newpath=%batchdir%%newpath%")
CALL :getresp "Apply new PATH=%newpath% [Y/N/Q]?"
IF /i "%response%"=="Y" ECHO SETX PATH "%newpath%"
GOTO :EOF

:addsegment
SET "segment=%~1"
IF /i NOT "%segment%"=="%batchdir%" SET "newpath=%newpath%;%segment%"
GOTO :eof

:getresp
SET "response="
SET /p "response=%~1 "
IF /i "%response%"=="Y" GOTO :eof
IF /i "%response%"=="Q" SET "response="&GOTO :eof
IF /i NOT "%response%"=="N" ECHO Please respond Y N or Q to quit&GOTO getresp
GOTO :eof

:showpath
ECHO(%path:;=&ECHO(%
GOTO :eof   

Essentially, the two batches are the same - the only difference is that for the INSTALL version, the directory is added into the path.

For this reason, I've simply desgned it so that thisbatch would install the file, and thisbatch /u would uninstall it.

Naturally, the calling of the routine to get a final OK to change the path is optional.

I don't know which options you require for the setx, so the command is simply ECHOed. You'd need to remove the ECHO from the SETX line to activate the setting of the path variable.

Note also that SETX does not set the target variable in existing or the current CMD instances - only those created in the future.

It's also important to remember that using the uninstall feature in this routine would remove the directory from the path without regard to the requirements of any other software.

查看更多
登录 后发表回答