How to insert a new path into a system path variable if it does not already exist

I use the following command to add the path to the Windows PATH variable:

setx PATH "%PATH%;%ProgramFiles%\MySQL\MySQL Server 5.5\bin" 

It works great.

My question is:

How to add the path (% ProgramFiles% \ MySQL \ MySQL Server 5.5 \ bin in this case) to the PATH variable of the system, and also check that it does not exist yet, and not add it twice if this happens?

+4
source share
2 answers
 @echo off setlocal EnableDelayedExpansion set "pathToInsert=%ProgramFiles%\MySQL\MySQL Server 5.5\bin" rem Check if pathToInsert is not already in system path if "!path:%pathToInsert%=!" equ "%path%" ( setx PATH "%PATH%;%pathToInsert%" ) 
+9
source

I think the easiest way is to check if it exists, and then join it if it does, or just write to it if it is not. From your tags, I assume that you are trying to do this from a batch file. This page seems to contain an example that fits you perfectly:

 IF "%PATH%" == "" GOTO NOPATH :YESPATH @ECHO The PATH environment variable was detected. PATH=C:\DOS;%PATH% GOTO END :NOPATH @ECHO The PATH environment variable was NOT detected. PATH=C:\DOS; GOTO END :END 

This batch code will add C: \ DOS to the path, just replace it with what you want to use. And, of course, you might want to delete echo lines or turn off alltogether echoes if you do not want messages to be displayed.

-1
source

Source: https://habr.com/ru/post/1485992/


All Articles