I am attempting to query the systems PATH variable in preparation of an update.
- If the old string exists, remove and append on new strings (x2) to beginning of the path.
- If the new strings are already in the path, then do nothing
- If neither the new or old are in the path, then append on new to beginning of the path.
I have wrote a batch, but it will break if the new path is already appended when I dont first clear out %errorlevel, OR if I clear the %errorlevel, it will simply add the new path on regardless if it is already there or not. I am sure there is an easier way to do this.
@echo off
setlocal enableextensions disabledelayedexpansion
type nul > C:\_sandbox\%computername%_PATH_UPDATE.log
echo %DATE% - %TIME% - PATH UPDATE started >> C:\_sandbox\%computername%_PATH_UPDATE.log
echo. >> C:\_sandbox\%computername%_PATH_UPDATE.log
echo Checking for OLD_PATH >> C:\_sandbox\%computername%_PATH_UPDATE.log
set "ErrorLevel="
echo %PATH% | FINDSTR /IX "C:\Program Files (x86)\OLD_PATH"
If %ErrorLevel%==0 goto 0
If %ErrorLevel%==1 goto 1
:0
set "ErrorLevel="
echo OLD_PATH found, removing and appending new path >> C:\_sandbox\%computername%_PATH_UPDATE.log
set NEWPATH=C:\Program Files (x86)\NEW_PATH;C:\Program Files (x86)\NEW_PATH2;%PATH:;C:\Program Files (x86)\OLD_PATH=%
setx PATH "%NEWPATH%" /m
exit /b 0
:1
set "ErrorLevel="
echo. >> C:\_sandbox\%computername%_PATH_UPDATE.log
echo OLD_PATH not found, checking for NEW_PATH >> C:\_sandbox\%computername%_PATH_UPDATE.log
echo %PATH% | FINDSTR /IX "C:\Program Files (x86)\NEW_PATH2"
If %ErrorLevel%==0 goto 2
If %ErrorLevel%==1 goto 3
:2
set "ErrorLevel="
echo NEW_PATH found, no further action required >> C:\_sandbox\%computername%_PATH_UPDATE.log
echo %path%
exit /b 0
:3
set "ErrorLevel="
echo NEW_PATH nor OLD_PATH were found, appending NEW_PATH >> C:\_sandbox\%computername%_PATH_UPDATE.log
set NEWPATH=C:\Program Files (x86)\NEW_PATH;C:\Program Files (x86)\NEW_PATH2;%PATH:;C:\Program Files (x86)\OLD_PATH=%
setx PATH "%NEWPATH%" /m
echo NEW_PATH Should of been appended. >> C:\_sandbox\%computername%_PATH_UPDATE.log
exit /b 0
I do not NEED it logged, however for testing I have been logging everything instead of using pauses as logging may prove useful for deployments. The Batch will be ran as SYSTEM which I imagine will require the users to relog.
In our instance, OLD PATH (FOR EXAMPLE) is C:\Program Files (x86)\Microsoft\Notepadv1.2 - Where as NEW_PATH is C:\Program Files (x86)\Microsoft\Notepad and C:\Program Files (x86)\Microsoft\Notepad_x64 respectively. That is why I query for NEW_PATH2 using /IX flags in FINDSTR.