Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch- string search on Windows PATH

I am writing an batch file in Windows to run post-installation scripts, and one of the things that needs to be done is to add a directory to the system path.

The script is working, and it does something like this:

setx Path "%PATH%;c:\path\to\add" -m

This is setting the path correctly, but this script could potentially be run multiple times if the user reinstalls the program.

I would like to search the string for c:\path\to\add so I don't keep adding the same path over and over to the system path. This is pretty trivial in Linux with sed, but I don't know what the command is in Windows. I've found findstr, but this seems to only work on files.

Is this possible in Windows without installing additional software?

EDIT:

I'm using Inno Setup to create the install executable.

like image 536
beatgammit Avatar asked Jul 11 '11 22:07

beatgammit


2 Answers

At the risk of some downvotes till an expert provides a sound way of doing this,
the below removes the specific path from the environment variable if it exists, so that it can be added again:

set str=%path%
:: str is the same with path

set str=%str:;C:\Path\To\Add=%
:: ";c:\path\to\add" is now removed from str

setx Path "%str%;c:\path\to\add" -m
:: proceed with setting the path


This carries the risk of removing the string if it is in fact actually a part of a path, for instance c:\path\to\add\somefolder. Also if the path actually ends with a \, or it is the first entry and it in fact does not start with ;, etc..

Various forms can be called consecutively to circumvent some of these,

set str=%str:;C:\Path\To\Add\;=;%
set str=%str:;C:\Path\To\Add;=;%
set str=%str:;C:\Path\To\Add\=%
set str=%str:C:\Path\To\Add\;=%
set str=%str:;C:\Path\To\Add=%

But, AAMOF I'n not sure this is a sane way of doing this..

like image 197
Sertac Akyuz Avatar answered Sep 28 '22 18:09

Sertac Akyuz


This is my code snippet to find the "cvsnt" path in the PATH variable.

if not "x%PATH:cvsnt=%" == "x%PATH%" goto proceed
set PATH=w:\build-repository\cvsnt\2.5.03-2382;%PATH%
echo Path added
:proceed

The part to look at is

not "x%PATH:cvsnt=%" == "x%PATH%"

First I replace all occurrences of "cvsnt" with an empty string. The result is compared to PATH without replacement of "cvsnt". If they are not equal because of "cvsnt" was replaced then it exists in PATH and the code can proceed.

The starting x before %PATH% is only a placeholder to protect against certain "improper" starting characters. see Batch file: Find if substring is in string (not in a file)

like image 36
Christoph Dittberner Avatar answered Sep 28 '22 16:09

Christoph Dittberner