You are not logged in.

#1 19 Dec 2015 14:05

Eehixohw
Member
Registered: 25 Sep 2011
Posts: 40

If exist in defined locations otherwise search

I have a script that requires an executable in order to work. Now, this executable can be anywhere but most of the time it is either in:

"%~d0\Keepass\Keepass.exe"
"%~dp0Keepass.exe"
"%PROGRAMFILES(X86)%\KeePass Password Safe 2\Keepass.exe"

The best I accomplished this is by multiple nested IF statements but it is really ugly and you must also type the path twice (one for checking and one for variable).

if exist "%~d0\KeePass\KeePass.exe" (
  set "keepassExec=%~d0\KeePass\KeePass.exe"
) else if exist "KeePass.exe" (
  set "keepassExec=%~dp0KeePass.exe"
) else if exist "%PROGRAMFILES(X86)%\KeePass Password Safe 2\Keepass.exe" (
  set "keepassExec=%PROGRAMFILES(X86)%\KeePass Password Safe 2\Keepass.exe"
)

The next bit should do a drive search if the exec is not found above but only on the root of each drive. Like the snippet below:

for %%a in (c d e f g h i j k l n m o p q r s t u v w x y z) do if exist %%a:\Keepass\Keepass.exe set KeepassExec=%%a:\Keepass\Keepass.exe 

I could use only this code but it delays the script quite a bit. And this will be launched on every system reboot so it should be fast.

Thank you for talking the time to help.

Offline

#2 19 Dec 2015 17:37

Aacini
Member
Registered: 05 Dec 2012
Posts: 149

Re: If exist in defined locations otherwise search

@echo off
setlocal

rem Define the list of paths to search, separated by semicolon
set "passPath=%~d0\Keepass;%~dp0;%PROGRAMFILES(X86)%\KeePass Password Safe 2"

rem Search the file in this path
for %%a in (Keepass.exe) do set "keepassExec=%%~$passPath:a"

if defined keepassExec goto continue
for %%a in (c d e f g h i j k l n m o p q r s t u v w x y z) do (
   if exist %%a:\Keepass\Keepass.exe (
      set "KeepassExec=%%a:\Keepass\Keepass.exe"
      goto continue
   )
)
:continue

For further details on the method used, see the description of replaceable parameters in FOR /? help, particularly the "%~$PATH:I" form one.

Last edited by Aacini (19 Dec 2015 23:53)

Offline

Board footer

Powered by