Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running batch file from USB drive when drive letter changes

Tags:

batch-file

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.

like image 531
anmolm97 Avatar asked Sep 30 '13 21:09

anmolm97


People also ask

How can I execute a bat file in a pen drive by just connecting the pen drive to the PC?

bat file to your flash drive, without putting it in a folder. You use Notepad to write the autorun. ini file as directed, and then save that to the flash drive. Then, insert it into your computer.

How do I change the drive in a batch file?

Use the /D switch to change current drive in addition to changing current directory for a drive. Show activity on this post. If you need to go from a device to another (in your case from C:\ to F:\ , you need to type F: before/after you entered your cd command, so it will go on the F device.


2 Answers

%~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
like image 183
JohnLBevan Avatar answered Oct 12 '22 13:10

JohnLBevan


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
like image 44
Michael Mulvey Avatar answered Oct 12 '22 11:10

Michael Mulvey