i have a problem that i've not found the solution after 1 hour of search on the net !
Situation :
I have a directory \DIR
In this directory I have a SCRIPT.lnk
that I would like targeting \DIR\Dependences\SCRIPT.bat
but the \DIR
folder will be portable (in an usb key or any other random directory).
Have you a solution to make them relatives ? I've tried multiple syntax type but, none works.
The solution is easy once you realize that batch files aren't executable. It's cmd.exe
that executes, which then interprets your batch script. With that in mind, you can point your shortcut to cmd.exe
in either its absolute fully-qualified path or as its traditional environment variable %comspec%
(or %windir%\system32\cmd.exe
if you prefer).
And now, since your bat file is no longer the target but is now an argument, you can make that relative all day long. Beauty is that if the shortcut is moved along with the folder containing the batch script to a different drive and a different depth, it'll still work.
<# : batch portion
@echo off & setlocal
set "shortcutname=script.lnk"
set "shortcuttarget=DIR\Dependences\SCRIPT.bat"
powershell -noprofile "iex (${%~f0} | out-string)"
goto :EOF
: end batch / begin PowerShell hybrid code #>
$shortcut = (new-object -COM WScript.Shell).CreateShortcut($env:shortcutname)
$shortcut.TargetPath = "%comspec%"
$shortcut.Arguments = '/c "{0}"' -f $env:shortcuttarget
$shortcut.Save()
And for anyone curious as to how this can be applied to shortcuts pointing to something other than a .bat script (such as a PDF document, for example), just replace the $shortcut.Arguments
line with this:
$shortcut.Arguments = '/c start "" "{0}"' -f $env:shortcuttarget