anmolm97
anmolm97

Reputation: 115

Running batch file from USB drive when drive letter changes

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.

Upvotes: 11

Views: 42483

Answers (3)

Michael Mulvey
Michael Mulvey

Reputation: 131

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

Upvotes: 2

JohnLBevan
JohnLBevan

Reputation: 24470

%~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

Upvotes: 22

CS Pei
CS Pei

Reputation: 11047

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

Upvotes: 0

Related Questions