Search code examples
windowsbatch-filewindows-8cmdshortcut

How do I create a shortcut via command-line in Windows?


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?


Solution

  • 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.