How to insert a new path into system path variable if it is not already there

Hamed Kamrava picture Hamed Kamrava · Jun 13, 2013 · Viewed 10.9k times · Source

I'm using the below command to append a path to windows system PATH variable :

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

It works fine.

My question is:

How to append a path (%ProgramFiles%\MySQL\MySQL Server 5.5\bin in this case) into system PATH variable while also checking that it is not already there, and not adding it twice if it does?

Answer

Aacini picture Aacini · Jun 13, 2013
@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%"
)