# How to create shortcuts with a relative path for use on USB drives

this posting will describe how to create program shortcuts on the root folder of a USB drive that preserve the relative path of the USB drive’s folder structure (such that these shortcuts will always work no matter what drive letter Windows assigns the drive).

It will also aim to preserve the icon of the application in the new shortcut.

The problem: say you have a portable app that in a folder on a USB drive with, for example, a path such as “F:\EjectUSB\EjectUSB.exe”. Say, moreover, that you would like to create a shortcut to “EjectUSB.exe” and place it on the root folder of your USB (“F:”, in this case). You might be tempted to simply copy a shortcut and place it on the root folder; except for one thing: that shortcut will always refer to “F:\EjectUSB\EjectUSB.exe”, and should you plug your USB drive into a computer that assigns a different letter to the USB drive (i.e. a letter than is not “F”) the shortcut will break down and not work. Hence the need for a shortcut with a relative path.

The solution:

• Windows does not support relative paths in shortcuts. Instead, this article will describe a solution based on creating a so-called batch (.BAT) file and converting that into an executable (which nonetheless displays the original program’s icon).
• I will use the example outlined above (“F:\EjectUSB\EjectUSB.exe”).

Step by step:

1. Create a new text document (to create a text document right click anywhere on your desktop, select new, then select “Text Document” from the context menu). Open it and type in the path for the executable, between quotes, without the drive letter and colon (e.g. “EjectUSB\EjectUSB.exe” – with the quotes). Save and exit. It does not matter what you name the file at this point, but let’s say you named it shortcut.txt for reference.
2. Rename the text file and change the extension to .BAT instead of .TXT.
3. Before we go further we have to extract the icon from the original app and save it as an ICO file. To do this use a program such as “BecyIconGrabber“. Download, extract, and run, then point to the original executable (“F:\EjectUSB\EjectUSB.exe” in this case). Right click on the icon when it appears (it doesn’t matter which size icon you are looking at) and save it as an ICO file.
4. Download and unzip the free “Bat To Exe Converter” and run it. In the program dialog, point to the batch file you created (shortcut.bat) for the”batchfile” field and to the extracted ICO file for the “Iconfile” field. Use the “Compile” button to complete the operation.
5. Two more things left to do (1) rename the new executable if you want to, and (2) move it to the root folder of your USB device.
6. That’s it. You can now run the new exe file from the USB’s root folder to launch your program; it will always preserve the relative path, no matter what letter Windows assigns the USB device.

#### Samer Kurdi

Has been reviewing software since 2006 when he started Freewaregenius.com

#### Latest posts by Samer Kurdi (see all)

• fred

It’s when I see such things I’m happy to use a real 100% portable file manager.

One of the so many excellent & addictive features of XYplorer (http://www.xyplorer.com) is its support for relative syntax. With that, when I use it, I can start application no matter what letter my USB stick got assigned, dbl-clicking on files like *.txt start my text editor without trouble either thanks to Portable File Associations…

This thing is so great it’s hard to believe. I know it’s not free, but with a lifetime license it’s well-worth the money. And of course, you can always find the last freeware version if you look for it…

• Samer

@Fred,
Pegtop PStart is a launcher is freeware and it also supports relative paths:
http://www.pegtop.net/start/

• Mark

Thanks, Samer. One question though. At some point I must have associated the BAT extension with Notepad, so now when I make the EXE and execute it, it just brings up my script in Notepad. How do I unassociate BAT files to get them to launch the script when the EXE files are executed?

• http://hi.baidu.com/knityster/blog/item/64bed82d86c62132359bf7be.html knityster

it’s perfect except this:
when i run the application, a black DOS windows will show at the same time ..

^_^

• OAlexander

@ Mark

>>>
REGEDIT4

[HKEY_CLASSES_ROOT\batfile\shell\edit]
[HKEY_CLASSES_ROOT\batfile\shell\edit\command]
[HKEY_CLASSES_ROOT\batfile\shell\open]
[HKEY_CLASSES_ROOT\batfile\shell\open\command]
@ = “\”%1\” %*”
<<>> and <<< into a Textfile with Notepad, save it as something like “bat.reg”, double click it, and BATchfiles should have regained their magic.

• OAlexander

Did not quite work as intended above.

@ Mark

!!!
REGEDIT4

[HKEY_CLASSES_ROOT\batfile\shell\edit]
[HKEY_CLASSES_ROOT\batfile\shell\edit\command]
[HKEY_CLASSES_ROOT\batfile\shell\open]
[HKEY_CLASSES_ROOT\batfile\shell\open\command]
@ = “\”%1\” %*”
!!!

Copy everything between the “!!!” (but without the “!!!”) into a Textfile with Notepad, save it as something like “bat.reg”, double click it, and BATchfiles should have regained their magic.

• Samer

@Mark,
I am not sure what the issue is but seems like OAlexander above has the info you need.

@knityser
Yes the black DOS dialog will appear, but should only be there for a second or so.

• http://mintywhite.com Rich

Samer,

I think this guide is great: thank you.

You can always assign a permanent letter to your USB — or any — drive in Windows.

• Arpit Jain

you could this nsis script i wrote to get a permanent letter on each pc you use your thumbdrive on just run it on any pc and you will get the letter you specified in the config file (if that letter is free) (Needs Administrator Privileges)

http://portableapps.com/node/11892

(i am known as tipra.wicked)

• Arpit Jain

sorry i didn’t check the link above
http://rapidshare.com/files/132521065/ReMount.zip
instructions Inside

• Anonymous

Nice Work

• anonymous coward

I’m happy (as always) that I use a decent operating system – one that uses a filesystem with support for relative symlinks. Oh, they have been in UNIX since 1983!
A quick search on the web reveals that ntfs has something like symlinks, but they are poorly documented and hard to handle.
And once you find yourself scripting around the deficencies of your operating-system, you’ll appreciate an OS with decent scripting support (Well, which family of OS could that be?).

• m^2

Sample: A .lnk that opens a.txt in own directory.

MIME-Version: 1.0
Content-Type: application/octet-stream; name=”a.txt.lnk”
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=”a.txt.lnk”

TAAAAAEUAgAAAAAAwAAAAAAAAEaKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

• AnotherApproach

You could achieve the same result in one step using a simple vbscript (.vbs) script file :-

sDriveLetter = Left(Wscript.ScriptFullname,2)
sRunCmd = sDriveLetter & “\folder\myprogram.exe”
set oWS = WScript.CreateObject(“WScript.shell”)
oWs.Run sRunCmd , 0, False

• Joe

An example of yet another approach using a default Windows shortcut (.lnk) file:

To start siw.exe using a shortcut placed in the same directory, enter the following as the target:

Win NT, 2000, XP, Vista: %windir%\system32\cmd.exe “/C start siw.exe”
Win 95, 98, ME: %windir%\system32\start.exe “siw.exe”

and then enter %cd% as the “Start In” directory.

Set it to run minimized, and the flash of the CMD window will only show up in your task bar.

You can use relative paths for “SIW/siw.exe” for a subdirectory, “../siw.exe” for the next-higher directory

• wm

this trick ALSO works on cd’s

• Wyatt

THANKYOU SO MUCH!!!!!

• Ryan

This worked great for me. Thanks a ton!!! Also, I found if you run the Bat To Exe Converter and, above the “Compile” button, if you select “Ghost application” instead of “Console application”, no DOS Shell popped up. Knityster, you might want to try this.

• http://robmaule.com Rob

Seems to work pretty well, except that I ran it on the GUI for JkDefrag and it put the INI in the root of the drive.

I find that the drive letter shifts to the correct letter if you use a shortcut anyway, though. Just doesn’t show the icon until the path changes.

• Stumpy

Joe’s Solution (5 up) is working great for me, and is the simplest.
Change the double quotes if you cut and paste his example, as they come out funny.

• dave

When I do this, the command doesn’t know that it has opened the program so the script stays open. Any thoughts?

• Alex

Doesn’t work for me. My batch file reads:
“\PDFV_Portable\PDFXCview.exe”
(quotes included)
Upon executing it, it launches PDF Viewer as expected.
After “compiling” it to EXE, I get a flashing window. Both EXE and BAT are in T:\

If I run the exe from the command prompt, I get the following result:
C:\DOKUME~1\Alex\LOKALE~1\Temp\232.tmp>”\PDFV_Portable\PDFXCview.exe”
Das System kann den angegebenen Pfad nicht finden.

First line suggests that the exe is launched from a temp directory (and not from t:\ where the exe resides)
Second line says that the system could not find the specified path (i.e. \PDFV_Portable), which is understandable, given the fact that it starts from C:\ and not T:\
So, while the problem is clear (program is executed from a different place), I don’t know the solution.

• suuk

when i tried to make the .bat file executable, my antivirus jumped right over it screaming it was a trojan horse. i don’t like this solution!

• ran

what if i want to run some .exe with command line?
like “abc\game” -console

• Firestorm

Won’t work for Launchy.
Here’s what I typed in:
“\PortableApps\Launchy\Launchy.exe”

I tested it with the portableapps menu and that one works
This is what I typed in for that one:

I’m stumped, why won’t ot work for launchy? The only dif is the last folder name and obviously the exe . I can run launchy manualy from there or from the portableapps menu but not from the bat/exe. :'(

• Jedi_Master_Revan@yahoo.ca

The scary part is, though I’ll never use this for what the article explains, but I’ll probably find a hundred other uses. Especially the icon thing. Thanks

• Moman256

Ok, if you guys don’t want a black DOS windows to pop up. Then, when you are making the conversion, check invisible application instead of visible application (the default)

I do it in a much more simpler way:
RelativePathForUSB.1.bat ->
start \usb\T\Test\Test1\Test1.txt

‘usb’ is a main directory.
You can store *.bat files in any directory on your usb drive, .. it will find any file/application on your usb drive.

I have improved on this slightly so that you can use command line options with the batch file, and pass it on. This also works with spaces, you just need to enclose them with quotations.

Simply use this template, and replace the 4th line down with your path from above, remembering the %* at the end.

@echo off
set count=0
call :loop %*
“Program Files\Support Tools\setx.exe” %*
goto :EOF
:loop
if !%1!==!! goto :EOF
shift
set /a count+=1
goto :loop

My mistake, I pasted the debug code. All you need is:

@echo off
“Program Files\Support Tools\setx.exe” %*

• Help?

on some public computers the cmd is disabled and you cant use it. any way to get past that?

• James

Best comment by Joe. This works flawlessly; no bat files, no extra applications to download. Of course, I only need these shortcuts for Vista/Win7. I have an autorun.inf in the root for shell integration in XP. (Best to mark it as read only.)

 shell=0cmd shellcmd=CMD NAME shellcmd\command=explorer \PATH\Path #clicking on the drive launches a window to specified folder.

 shell=1KPX shell\1KPX=1. KeePassX shell\1KPX\command=PATH\Path\KeePassX.exe #right click drive, click on '1. KeePassX' to launch KeePassX shell=2True shell\2True=2. TrueCrypt shell\2True\command= PATH\Path\TrueCrypt.exe /v PATH\Path\volume #right click drive, click on '2. TrueCrypt' to launch TrueCrypt to a #specified volume. 

shell=3dismounttc shell\3dismounttc=3. Dismount shell\3dismounttc\command=PATH\Path\TrueCrypt.exe /d /q #right click drive, click on '3. Dismount' to dismount TrueCrypt #volumes and exit program. 

• CMedina

I’ve found another way.. it is pretty simple but will leave you a cmd window opened until main application is closed.

1. Create a Shortcut

2. Just write in “Traget:
%windir%\system32\cmd.exe /c cd “__RELPATH_TO_MY_WORKING_DIR__” & “__APP_NAME__”

3. In the “Start In:” (Leave it blank)

Note:
I dont know if using the command
cd approach will work for you as “Start In:” does but it worked for me.

Also, you can set “Run:” to minimized but will leave window still opened… I hate that window!

• Wouter Lievens

This is not good enough, unfortunately. Virus scanners will not pick up on the shortcut, but they will complain about the executable you create

• Giovanni Guerrero

Thanks a lot!!! I’ve learned something new today. It worked immediately and if you pay attention to the options in the bat to exe program you can hide the cmd window.

Again, thanks for a nice lesson. By the way, so far Avast Free Antivirus (which I consider as a very good antivirus) hasn’t said anything yet about any of my new shortcuts.

• Nyerguds

just a batch file works… make a .txt file, aff one of the following bits in it, and rename it from .txt to .bat

——

::Open folder:
@start path\to\open\in\explorer\

——

::Open file of any type:
@start path\of\file\file.txt

——

::start application:
@echo off
cd path\of\application\
start /i application.exe

——

The “@” before the line and the “@echo off” at the start of the file have the same function, btw. They suppress explicitly showing the executed commands ( = the text in the .bat file) in the console. Since it’ll only show for a single secons, it won’t matter much anyway.

• Nyerguds

Oh, for a shortcut to a to folder to open in Explorer, you can use this:

%SystemRoot%\explorer.exe /e,relative_path_to_open\

This is actually an adaptation of the trick to open an explorer set to the My Computer folder, which is

%SystemRoot%\explorer.exe /e,::{20d04fe0-3aea-1069-a2d8-08002b30309d}

But I figured a relative path would work too behind the /e, and I was right

• RpD

In WinXP and newer, another way to run commands from your USB drive, and set the ‘current drive’ in batch files on your USB drive, is to use:

%cd:~0,2% …for the drive letter

It’s a little cmd.exe interpreter magic for getting the current drive letter. Just place %cd:~0,2% in front of your USB drive program’s path, rather than an explicit drive letter.

For example:

“%cd:~0,2%\EjectUSB\EjectUSB.exe”

…will execute EjectUSB.exe from the ‘current drive’ (your USB drive), when you execute your batch file command -from- the USB drive.

Works also for batch files converted to exe’s… and, if you set the ‘ghost’ or ‘invisible’ parameter in the converter, there will be -no- extraneous windows or taskbar flickers. Also, in bat_to_exe v1.5, the icon inclusion is under the Versioninformations tab.

For batch files, you can include @ECHO OFF to suppress command display (even though the command window usually merely blinks up for a split-second), for example:

@ECHO OFF
“%cd:~0,2%\EjectUSB\EjectUSB.exe”
EXIT

Note: Using cmd.exe /c …in a shortcut, may have problems if you have spaces in your USB program’s path, such as:
\Program Files\path\program.exe
…and the shortcut won’t allow for parameters to follow the program.exe.

However, using %cd:~0,2% will allow parameters, for example:

“%cd:~0,2%\path\program.exe” /x /y /z “abc”

• RpD

Meant to say:

However, using %cd:~0,2% (in a batch file) will allow parameters, for example:

“%cd:~0,2%\path\program.exe” /x /y /z “abc”

• gus

to summer:
this sofware is very cool, did anybody try it? solve all problems with usb applications
thx

**********************
Samer says:
July 24, 2008 at 7:12 pm

@Fred,
Pegtop PStart is a launcher is freeware and it also supports relative paths:
http://www.pegtop.net/start/

• gus

i was inspired by PStart application and find this
http://www.portablefreeware.com/?sc=116

i like qsel
but there are lot of this type of application

• Mark

To get rid of the black window choose the invisible optiopn.

• http://erichamiter.com/ Eric

This worked great. One thing to note: your quotation marks as-is are not formatted correctly, so it initially was not working for me. After I replaced the “curly” quotations with standard “straight” ones, it worked immediately.

Thanks!

• Troy K

You can do it with a shortcut…
%windir%\explorer.exe /e,..\..\..\..\My folder

• wguru

Great stuff here, but is there a way to chnage a batch of shortcut (say all found in one folder) to another drive letter? I have some 6,000 shortcuts and half of them traget and start in the wrong drive letter (so they don;t work and I would have to manually change 3,000 shortcut proerties if no other means to fix this). Again all 6,000 are on one drive, but due to Windows annoyingly changing EHD drive letters simple minded by the drive’s introduction to the pc, I ended up not noticing the drive letter didn;t match the other 3000 shortcuts.

• wguru

Wouldn’t purposely double post, but the initial try at posting seemed to fail as I was promted with something like, the server was unavailable, try back later. So I immiediatley back paged, re-wrote (but didn’t check to see if it previously poseted as I assumed it had, given the promt about ‘busy and try back later’).

• Samer

wguru,
Don’t worry about the double posting. Its a problem with my host.

• wguru

Ref. fixing ‘rogue’ drive letter assigned shortcuts, my Googling the issue (Changing target path of windows shortcuts) resulted in one forum suggesting use of a powershell script file. However, someone there instead recommends that it might be better to use code to change all the shortcut’s to the drive letter of choice. So I’m currently awaiting that person’s kkindly afforded instruction/details.

• Drew

Shortcuts do support relative paths, but the wizard which creates them doesn’t.
So:
1. Create a shortcut as normal using the full path.
2. Edit the shortcut with a binary editor, such as Visual Studio Express (free)
2a. Some binary editors open the exe file the shortcut points to instead of the shortcut. To work around this, rename the file from xxx.lnk to xxx.bin, then open it again
3. Find the full path in the data, by doing a search
4. Copy the relative path over the full path
5. Find a 00 in the binary, copy it over first extra character in the full path
6. Save the file
6.a If you did 2a, rename the file back to .lnk
7. Run the shortcut – should work

• Samer

@ Drew: thank for sharing!

• Eviler

Very nice! Just what i was looking for! Thank you.

• Norville Cole

Hi,
How do you include an option to change a init directory

I:\gns3\GNS3.exe –configdir I:\GNS3

Thanks
Norville

• Martin Podbi

Hi,
This tutorial is great indeed. But I’ve got one question. How to run some program with additional parametrs. For example, I would like to have shortcut to “G:\NetBeans\bin\netbeans.exe” there is now trouble. But if i want run it with additional parameter “–console suppress” it won’t work. In my “bat” file I’ve placed the following: “NetBeans\bin\netbeans.exe –console suppress” and Windows command line won’t run it. It writes some message about don’t knowing if this is internal, or external program.
Can anyone help?

Thanks

• Abcd

@Martin… try “”NetBeans\bin\netbeans.exe” “-console suppress””

• Alex

Thank you very much

• LouD

Give this variation a try:

This Batch-file is executed via a desktop shortcut AFTER a memory device is plugged into ANY available usb port.

It searches possible drive letter assignments IN REVERSE ORDER from Z to G
(excluding C D E & F) looking for the App (Bing.Bat) and executes it if it is found within that memory device on the specified path. The root directory In this case.

Batchfile:
FOR %%i in (Z Y X W V U T S R Q P O N M L K J I H G) DO (IF exist %%i:\BING.BAT %%i:\BING.BAT)

or:

Direct Command line:
FOR %i in (Z Y X W V U T S R Q P O N M L K J I H G) DO (IF exist %i:\BING.BAT %i:\BING.BAT)

Find and copy the App’s icon from its normal location and put in with existing icons or change where the desktop shortcut should look for it.

• Samer

@ LouD: thanks for this. Great tip!

• Eric

Thanks for the tutorial. It is just what I was looking for. My experience:

When I compiled and ran the new .exe, it left an unnecessary command prompt open. To solve this, I recompiled the .exe using the “invisible application” application. This is found in the Options tab in the Visibility box.

Oddly, doing so slightly changed the behavior of the “User Account Control” window that pops up in Windows 7. The new behavior is slightly less favorable but I’m keeping it over the leftover command prompt window.

• Eric

Correction: I recompiled the .exe using the “invisible application” option.

• Eric

UPDATE:

I found a better way to launch the application without a lingering command prompt. Format the .bat like this:

start “” Path\Program.exe

Run the .bat to make sure it works properly. When it does, use the Bat to Exe Converter to compile the .bat with the icon file as in the instructions in the original post. You could also skip this step and just use the .bat file as your shortcut if you don’t care about the icon. Sorry for the triple post.

• Jay

Sweet!! Worked for me. Thanks dude.

• Anonymous

you are the best! big thenks!

• Danny

Has anyone tried then on a CD? You run into the same issues when trying to create a shortcut on a CD. Hopefully the solution will work the same way.

I plan to try later today, and will post the results.

• Danny

Has anyone tried then on a CD? You run into the same issues when trying to create a shortcut on a CD. Hopefully the solution will work the same way.

I plan to try later today, and will post the results.

• http://abdoulaye.com Abdoulaye Siby

Try this in the target …

cmd /c “relative-path-to-the-exe/file.exe”

• santana

I hop this will be a variant of solution

START “relative-path-to-the-File/anyfile”

not only .exe .chm .pdf ….

have a nice day

• Thiago

Really helped …
Thank you.

• Samer Kurdi

I just found this small freeware application, that provides a quick solution
http://www.horstmuc.de/wminis.htm#shortexe

• White Geared

A little correction: “EjectUSB\EjectUSB.exe” would be “\EjectUSB\EjectUSB.exe”.

• Bas Groothedde

“EjectUSBEjectUSB.exe” refers to the root of a drive, which is only relative to the drive root. For true relative paths, ommit the first backslash.

• Disgruntled User

DO NOT ATTEMPT!

“Bat To Exe Converter” is loaded with trojans. Tried to compile the EXE from the BAT and my AV software went apeshit. It caught 4 attempted installs of malicious software. Plus, because the installs were blocked, the program spit out an error and didn’t build the EXE.

• AZLK
• Karim Bahgat

The solution in this post is great but has a shortcoming. It only seems to work if the shortcut/exe file is in the top-directory of a USB stick, but does not work if it is in a subfolder anywhere else or on a local computer. As such, the shortcut solution only partially supports relative paths and does not make the program truly transportable.

A quick modification of the procedure will however allow full relative paths:
2 – write: %windir%system32cmd.exe /c start “” “%CD%optional subfoldermainpy2exeGUI.exe”
3 – save as “whatever.bat”
4 – convert the bat-file to an exe file using the “BAT to EXE converter” program while checking the “invisible application” option, and selection the icon file you want under the “versioninformations” tab. You can name the output exe file to whatever you want.

This modified solution is different in terms of the code it uses in step2 which allows the launcher progam to be placed anywhere on a computer and not just on the top directory of a USB-stick, and is new to emphasize that the invisible option should be checked. Those differences are crucial.

With this method, you will be able to create a standalone exe program launcher that can be placed anywhere and refer to a file in its subdirectory, while having a pretty icon of your choice and no DOS screen popping up.

In other words, a true good-looking relative-path transportable shortcut file

• Mike Mounier

You da man, works like a charm and is best solution I’ve seen thus far.

Might also work by first pointing to explorer.exe (rather than cmd.exe) but haven’t tried it… not that there’s any pressing reason to change it.

• AJ S

Hey cool the icon program has a Trojan embedded within it (found by my sonicwall gateway antivirus and then confirmed by SEP) and the .zip downloaded by the CNET installer gives a message that it is invalid and will not extract. Cool stuff.

• John Trizna

Action script file: Sample.hta

fso = new ActiveXObject(“Scripting.FileSystemObject”);
function Run(Prog) {
var aPath = fso.GetAbsolutePathName(“.”);
var lnk = aPath+’\’+Prog;
var shell = new ActiveXObject(“WScript.Shell”);
shell.Run(lnk);
self.close();
}
Run(‘path relative-to-the-Sample.hta\some-program.EXE’);