59

I want my .bat script (test.bat) to create a shortcut to itself so that I can copy it to my windows 8 Startup folder.

I have written this line of code to copy the file but I haven't yet found a way to create the said shortcut, as you can see it only copies the script.

xcopy "C:\Users\Gabriel\Desktop\test.bat" "C:\Users\Gabriel\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

Can you help me out?

Maslor
  • 1,821
  • 3
  • 20
  • 44

11 Answers11

73

You could use a PowerShell command. Stick this in your batch script and it'll create a shortcut to %~f0 in %userprofile%\Start Menu\Programs\Startup:

powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Start Menu\Programs\Startup\%~n0.lnk');$s.TargetPath='%~f0';$s.Save()"

If you prefer not to use PowerShell, you could use mklink to make a symbolic link. Syntax:

mklink saveShortcutAs targetOfShortcut

See mklink /? in a console window for full syntax, and this web page for further information.

In your batch script, do:

mklink "%userprofile%\Start Menu\Programs\Startup\%~nx0" "%~f0"

The shortcut created isn't a traditional .lnk file, but it should work the same nevertheless. Be advised that this will only work if the .bat file is run from the same drive as your startup folder. Also, apparently admin rights are required to create symbolic links.

rojo
  • 24,000
  • 5
  • 55
  • 101
  • 1
    aah.+1. Forgot about mklink. Though it is supported on vista and above (anyway XP is on the way to the graveyard) and is not so rich on options. Powershell solution is much better :) – npocmaka May 04 '15 at 12:26
  • 2
    Yeah, but powershell will cause a second's pause if it hasn't been primed for the current Windows session yet. Your shortcutJS.bat solution should be faster. – rojo May 04 '15 at 12:31
  • 1
    I think that the mklink solution enough for the current project I'm doing, I don't see the need for a better yet more complex command. But there's something I need to bypass: *admin rights*. Is there an option to configure user rights in mklink? – Maslor May 04 '15 at 14:54
  • 2
    Using group policy editor you can modify `Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment` according to [this page](http://ss64.com/nt/mklink.html). There's also a way you can have your script prompt for UAC using a [chunk of VB Script](https://sites.google.com/site/eneerge/home/BatchGotAdmin). Honestly, I think the PowerShell command or npocmaka's shortcutJS.bat solution will result in the best user experience. – rojo May 04 '15 at 15:02
  • 2
    A filesystem symbolic link is fine for a file that will be run/opened via `ShellExecuteEx` or a bat/cmd script for which `CreateProcess` hard codes running the `%ComSpec%` command interpreter. But it won't work for an .exe (specifically a PE executable, regardless of extension) that looks for resources relative to the application directory. Thus unless the link is created in the same directory (e.g. `prog.2.0.exe` => `prog.exe`), a .lnk shortcut is generally the better solution. – Eryk Sun May 04 '15 at 19:24
  • I'd like it to run without "asking for permission" so I was looking for a way to define rights in the batch itself – Maslor May 04 '15 at 20:14
  • @rojo Very good! Now I can use this in a batch file stored in my shell:sendto folder so that it will create shortcuts in my favourites folder. Just a small correction: I think it should be `%~nx1` and `%~f1`, since `%~0` is the name of the batch script itself and not the file that gets passed to the batch file. – Andreas Feb 09 '17 at 07:27
  • `mklink` (without switches) creates a symbolic link, not a `.lnk` shortcut – Saran Mar 03 '20 at 13:45
  • the powershell version no need UAC... it is pervect! Thank you! – Riccardo Bassilichi Aug 31 '20 at 14:20
20

Cannot be done with pure batch.Check the shortcutJS.bat - it is a jscript/bat hybrid and should be used with .bat extension:

call shortcutJS.bat -linkfile "%~n0.lnk" -target  "%~f0" -linkarguments "some arguments"

With -help you can check the other options (you can set icon , admin permissions and etc.)

npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • 2
    Great, it works very well. I think It's better than mklink method. I use shortcutJs.bat to create a shortcut for a .pyw file, the shortcut works exactly the same as the one created manually. But when you double click the link created by mklink, it can't auto find pythonw.exe to execute the .pyw file. – lengxuehx Jul 19 '16 at 04:49
  • I'm having problems adding a double quote inside the linkarguments, how do you add a double quote in the args? – MDuh Jun 04 '19 at 19:06
  • @MDuh - I'll have to update the script in order to support this. Probably during the weekend. – npocmaka Jun 05 '19 at 06:22
12

Rohit Sahu's answer worked best for me in Windows 10. The PowerShell solution ran, but no shortcut appeared. The JScript solution gave me syntax errors. I didn't try mklink, since I didn't want to mess with permissions.

I wanted the shortcut to appear on the desktop. But I also needed to set the icon, the description, and the working directory. Note that MyApp48.bmp is a 48x48 pixel image. Here's my mod of Rohit's solution:

@echo off
cd c:\MyApp
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "%userprofile%\Desktop\MyApp.lnk" >> CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.TargetPath = "C:\MyApp\MyApp.bat" >> CreateShortcut.vbs
echo oLink.WorkingDirectory = "C:\MyApp" >> CreateShortcut.vbs
echo oLink.Description = "My Application" >> CreateShortcut.vbs
echo oLink.IconLocation = "C:\MyApp\MyApp48.bmp" >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript CreateShortcut.vbs
del CreateShortcut.vbs
DrFractal
  • 121
  • 1
  • 5
  • 1
    I wanted a very simple solution to a very simple problem and I have already been given it. I was trying to just use BAT, not visual basic. – Maslor Jan 28 '16 at 00:23
  • 2
    But thanks for the answer! Might help someone else that comes here looking for solutions. – Maslor Jan 28 '16 at 00:23
  • 1
    I had problems getting the Desktop path in a Terminal Server where users were using custom Desktop location. To solve this, I had to read the Desktop location from the registry. `Set objShell = CreateObject("WScript.Shell") strRegDesktopPath = objShell.RegRead("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Desktop") desktopPath = objShell.ExpandEnvironmentStrings(strRegDesktopPath) Set oWS = WScript.CreateObject("WScript.Shell") sLinkFile = desktopPath & "\MyApp.lnk"` – Rodrigo V May 12 '17 at 22:28
9

The best way is to run this batch file. open notepad and type:-

@echo off
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "GIVETHEPATHOFLINK.lnk" >> CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.TargetPath = "GIVETHEPATHOFTARGETFILEYOUWANTTHESHORTCUT" >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript CreateShortcut.vbs
del CreateShortcut.vbs

Save as filename.bat(be careful while saving select all file types) worked well in win XP.

Rohit Sahu
  • 91
  • 1
  • 3
5

Nirsoft's NirCMD can create shortcuts from a command line, too. (Along with a pile of other functions.) Free and available here:

http://www.nirsoft.net/utils/nircmd.html

Full instructions here: http://www.nirsoft.net/utils/nircmd2.html#using (Scroll down to the "shortcut" section.)

Yes, using nircmd does mean you are using another 3rd-party .exe, but it can do some functions not in (most of) the above solutions (e.g., pick a icon # in a dll with multiple icons, assign a hot-key, and set the shortcut target to be minimized or maximized).

Though it appears that the shortcutjs.bat solution above can do most of that, too, but you'll need to dig more to find how to properly assign those settings. Nircmd is probably simpler.

4

To create a shortcut for warp-cli.exe, I based rojo's Powershell command and added WorkingDirectory, Arguments, IconLocation and minimized WindowStyle attribute to it.

powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Start Menu\Programs\Startup\CWarp_DoH.lnk');$s.TargetPath='E:\Program\CloudflareWARP\warp-cli.exe';$s.Arguments='connect';$s.IconLocation='E:\Program\CloudflareWARP\Cloudflare WARP.exe';$s.WorkingDirectory='E:\Program\CloudflareWARP';$s.WindowStyle=7;$s.Save()"

Other PS attributes for CreateShortcut: https://stackoverflow.com/a/57547816/4127357

pureocean
  • 61
  • 3
  • cool trick, works well also for user-context based operations like from a BAT or CMD file – ZAY Jun 01 '23 at 16:51
3

link.vbs

set fs  = CreateObject("Scripting.FileSystemObject")
set ws  = WScript.CreateObject("WScript.Shell")
set arg = Wscript.Arguments

linkFile = arg(0)

set link = ws.CreateShortcut(linkFile)
    link.TargetPath = fs.BuildPath(ws.CurrentDirectory, arg(1))
    link.Save

command

C:\dir>link.vbs ..\shortcut.txt.lnk target.txt
CodeFu
  • 39
  • 1
3

I would like to propose different solution which wasn't mentioned here which is using .URL files:

set SHRT_LOCA=%userprofile%\Desktop\new_shortcut2.url
set SHRT_DEST=C:\Windows\write.exe
echo [InternetShortcut]> %SHRT_LOCA%
echo URL=file:///%SHRT_DEST%>> %SHRT_LOCA%
echo IconFile=%SHRT_DEST%>> %SHRT_LOCA%
echo IconIndex=^0>> %SHRT_LOCA%

Notes:

  • By default .url files are intended to open web pages but they are working fine for any properly constructed URI
  • Microsoft Windows does not display the .url file extension even if "Hide extensions for known file types" option in Windows Explorer is disabled
  • IconFile and IconIndex are optional
  • For reference you can check An Unofficial Guide to the URL File Format of Edward Blake
n3vermind
  • 296
  • 1
  • 6
  • 1
    Yet, when one uses `IconFile`, then `IconIndex` is mandatory, even if icon file is an *.ico file (index should be 0 then, just as in the example). – Cromax Mar 12 '20 at 20:29
  • 1
    Under Win 8.1N at least, the last line should be "echo IconIndex=^0>> %SHRT_LOCA%". Without that, the line ends up in the console, not in the file, because Cmd.EXE treats "0>>" as redirecting the echo to StdOut. Handle Zero is StdIn and StdOut is handle One, but the "^" escapes the redirection regardless. – Bilbo Dec 16 '20 at 20:23
2

I present a small hybrid script [BAT/VBS] to create a desktop shortcut. And you can of course modifie it to your purpose.

@echo off
mode con cols=87 lines=5 & color 9B
Title Shortcut Creator for your batch and applications files by Hackoo 2015
Set MyFile=%~f0
Set ShorcutName=HackooTest
(
echo Call Shortcut("%MyFile%","%ShorcutName%"^)
echo ^'**********************************************************************************************^)
echo Sub Shortcut(ApplicationPath,Nom^)
echo    Dim objShell,DesktopPath,objShortCut,MyTab
echo    Set objShell = CreateObject("WScript.Shell"^)
echo    MyTab = Split(ApplicationPath,"\"^)
echo    If Nom = "" Then
echo    Nom = MyTab(UBound(MyTab^)^)
echo    End if
echo    DesktopPath = objShell.SpecialFolders("Desktop"^)
echo    Set objShortCut = objShell.CreateShortcut(DesktopPath ^& "\" ^& Nom ^& ".lnk"^)
echo    objShortCut.TargetPath = Dblquote(ApplicationPath^)
echo    ObjShortCut.IconLocation = "Winver.exe,0"
echo    objShortCut.Save
echo End Sub
echo ^'**********************************************************************************************
echo ^'Fonction pour ajouter les doubles quotes dans une variable
echo Function DblQuote(Str^)
echo    DblQuote = Chr(34^) ^& Str ^& Chr(34^)
echo End Function
echo ^'**********************************************************************************************
) > Shortcutme.vbs
Start /Wait Shortcutme.vbs
Del Shortcutme.vbs
::***************************************Main Batch*******************************************
cls
echo Done and your main batch goes here !
echo i am a test 
Pause > Nul
::********************************************************************************************
Hackoo
  • 18,337
  • 3
  • 40
  • 70
1

I created a VB script and run it either from command line or from a Java process. I also tried to catch errors when creating the shortcut so I can have a better error handling.

Set oWS = WScript.CreateObject("WScript.Shell")
shortcutLocation = Wscript.Arguments(0)

'error handle shortcut creation
On Error Resume Next
Set oLink = oWS.CreateShortcut(shortcutLocation)
If Err Then WScript.Quit Err.Number

'error handle setting shortcut target
On Error Resume Next
oLink.TargetPath = Wscript.Arguments(1)
If Err Then WScript.Quit Err.Number

'error handle setting start in property
On Error Resume Next
oLink.WorkingDirectory = Wscript.Arguments(2)
If Err Then WScript.Quit Err.Number

'error handle saving shortcut
On Error Resume Next
oLink.Save
If Err Then WScript.Quit Err.Number

I run the script with the following commmand:

cscript /b script.vbs shortcutFuturePath targetPath startInProperty

It is possible to have it working even without setting the 'Start in' property in some cases.

0

Based on Rohit's answer, I created this batch script which accepts the input parameters: AppPath, AppName, AppExtension and ShortcutDestinationPath.

MakeShortcut.bat:

@echo off

set AppPath=%~1
set AppName=%~2
set AppExtension=%~3
set ShortcutDestinationPath=%~4

cd %AppPath%
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "%ShortcutDestinationPath%\%AppName%.lnk" >> CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.TargetPath = "%AppPath%\%AppName%.%AppExtension%" >> CreateShortcut.vbs
echo oLink.WorkingDirectory = "%AppPath%" >> CreateShortcut.vbs
echo oLink.Description = "%AppName%" >> CreateShortcut.vbs
echo oLink.IconLocation = "%AppPath%\%AppName%.bmp" >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript CreateShortcut.vbs
rem del CreateShortcut.vbs

Example usage to create a shortcut to C:\Apps\MyApp.exe in the folder C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp:

MakeShortcut.bat "C:\Apps" "MyApp" "exe" "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"
datchung
  • 3,778
  • 1
  • 28
  • 29