windowsbatch-filesetx

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


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?


Solution

  • @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%"
    )