11

So, I have made a batch script and it executes multiple portable programs (e.g., prog1.exe, prog2.exe, etc). The problem is whenever I connect the USB drive to another computer, the drive letters change, giving me errors when running my .bat file. Please help me find a solution. Thank you.

indiv
  • 17,306
  • 6
  • 61
  • 82
anmolm97
  • 115
  • 1
  • 1
  • 6
  • 1
    Is the batch file hosted on the USB, or is the batch file local and the USB holds another resource that you're trying to access? – JohnLBevan Sep 30 '13 at 21:16
  • If the batch is hosted on the USB (as JohnLBevan has asked), forget this question (and use %~d0). Otherwise: Is fixing the drive letter on the computers an option? – Sebastian Sep 30 '13 at 21:20

3 Answers3

21

%~d0 gives you the current drive letter (including the colon). If the batch file's contained on the USB drive, you can use that.

So, for instance, instead of

E:\PortablePrograms\ProgramName.exe

you would write

%~d0\PortablePrograms\ProgramName.exe

... or you could do something like this

::change directory to the script's directory's drive
pushd %~d0
::navigate from the drive to the relevant path(s)
cd PortablePrograms
::execute any programs
ProgramName.exe
SecondProgramName.exe
::just because I like to pair my pushes with pops; not required
popd
JohnLBevan
  • 22,735
  • 13
  • 96
  • 178
2

This is how I get the last removable drive in a listing.

    @echo off

    :: Drivetypes
    ::  0=Unknown
    ::  1=No Root Directory
    ::  2=Removable(USB,Firewire)
    ::  3=Local Disk (Internal Hard Drive)
    ::  4=Network Drive(\\Server\share\)
    ::  5=Compact Disk (CD DVD)
    ::  6=Ram Disk
    for /f "tokens=2 delims==" %%d in ('wmic logicaldisk where "drivetype=2" 
    get name /format:value') do set driveletter= %%d
    echo %driveletter%
    pause
Michael Mulvey
  • 131
  • 1
  • 9
0

you can use command line argument %1, %2 as input path, and modify your bat file accordingly.

CS Pei
  • 10,869
  • 1
  • 27
  • 46