How to make a shortcut from CMD?

1,518

Solution 1

There is some very useful information on this site: http://ss64.com/nt/shortcut.html

Seems like there is some shortcut.exe in some resource kit which I don't have.
As many other sites mention, there is no built-in way to do it from a batch file.

But you can do it from a VB script:

Optional sections in the VBscript below are commented out:

Set oWS = WScript.CreateObject("WScript.Shell")
sLinkFile = "C:\MyShortcut.LNK"
Set oLink = oWS.CreateShortcut(sLinkFile)
    oLink.TargetPath = "C:\Program Files\MyApp\MyProgram.EXE"
 '  oLink.Arguments = ""
 '  oLink.Description = "MyProgram"   
 '  oLink.HotKey = "ALT+CTRL+F"
 '  oLink.IconLocation = "C:\Program Files\MyApp\MyProgram.EXE, 2"
 '  oLink.WindowStyle = "1"   
 '  oLink.WorkingDirectory = "C:\Program Files\MyApp"
oLink.Save

So, if you really must do it, then you could make your batch file write the VB script to disk, invoke it and then remove it again. For example, like so:

@echo off
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "%HOMEDRIVE%%HOMEPATH%\Desktop\Hello.lnk" >> CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.TargetPath = "C:\Windows\notepad.exe" >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript CreateShortcut.vbs
del CreateShortcut.vbs

Running the above script results in a new shortcut on my desktop:
Resulting shortcut

Here's a more complete snippet from an anonymous contributor (updated with a minor fix):

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET LinkName=Hello
SET Esc_LinkDest=%%HOMEDRIVE%%%%HOMEPATH%%\Desktop\!LinkName!.lnk
SET Esc_LinkTarget=%%SYSTEMROOT%%\notepad.exe
SET cSctVBS=CreateShortcut.vbs
SET LOG=".\%~N0_runtime.log"
((
  echo Set oWS = WScript.CreateObject^("WScript.Shell"^) 
  echo sLinkFile = oWS.ExpandEnvironmentStrings^("!Esc_LinkDest!"^)
  echo Set oLink = oWS.CreateShortcut^(sLinkFile^) 
  echo oLink.TargetPath = oWS.ExpandEnvironmentStrings^("!Esc_LinkTarget!"^)
  echo oLink.Save
)1>!cSctVBS!
cscript //nologo .\!cSctVBS!
DEL !cSctVBS! /f /q
)1>>!LOG! 2>>&1

Solution 2

Here's a similar solution using powershell (I know, you can probably re-write your whole batch file in PS, but if you just want to Get It Done™...)

set TARGET='D:\Temp'
set SHORTCUT='C:\Temp\test.lnk'
set PWS=powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile

%PWS% -Command "$ws = New-Object -ComObject WScript.Shell; $s = $ws.CreateShortcut(%SHORTCUT%); $S.TargetPath = %TARGET%; $S.Save()"

You may have to explicity specify the path to PS in your file, but it should work. There are some additional attributes you can mangle through this object, too:

Name             MemberType Definition                             
----             ---------- ----------                             
Load             Method     void Load (string)                     
Save             Method     void Save ()                           
Arguments        Property   string Arguments () {get} {set}        
Description      Property   string Description () {get} {set}      
FullName         Property   string FullName () {get}               
Hotkey           Property   string Hotkey () {get} {set}           
IconLocation     Property   string IconLocation () {get} {set}     
RelativePath     Property   string RelativePath () {set}           
TargetPath       Property   string TargetPath () {get} {set}       
WindowStyle      Property   int WindowStyle () {get} {set}         
WorkingDirectory Property   string WorkingDirectory () {get} {set} 

Solution 3

Besides shortcut.exe, you can also use the command line version of NirCmd to create shortcut. http://nircmd.nirsoft.net/shortcut.html

Solution 4

How about using mklink command ? C:\Windows\System32>mklink Creates a symbolic link.

MKLINK [[/D] | [/H] | [/J]] Link Target

    /D      Creates a directory symbolic link.  Default is a file
            symbolic link.
    /H      Creates a hard link instead of a symbolic link.
    /J      Creates a Directory Junction.
    Link    specifies the new symbolic link name.
    Target  specifies the path (relative or absolute) that the new link
            refers to.

Solution 5

After all the discussions we had here, this is my suggested solution: download: http://optimumx.com/download/Shortcut.zip extract it on your desktop (for example). Now, suppose you want to create a shortcut for a file called scrum.pdf (also on desktop):
1. open CMD and go to desktop folder
2. run: Shortcut.exe /f:"%USERPROFILE%\Desktop\sc.lnk" /a:c /t:%USERPROFILE%\Desktop\scrum.pdf

it will create a shortcut called sc.lnk on your desktop that will point to the original file (scrum.pdf)

Share:
1,518

Related videos on Youtube

Mahmoud Moustafa
Author by

Mahmoud Moustafa

Updated on September 18, 2022

Comments

  • Mahmoud Moustafa
    Mahmoud Moustafa over 1 year

    This is another I'm-totally-new-to-Ruby-please-have-mercy situation.

    So i'm trying to figure out how to make a database of all my buttons to save the click count each time they're clicked. I started a new rails to try it out and generated a model Buttonand a controller buttons index

    route.rbs

    Rails.application.routes.draw do
      resources :buttons
      root 'buttons#index'
    end
    

    migration

    class CreateButtons < ActiveRecord::Migration[5.0]
      def change
        create_table :buttons do |t|
          t.integer :clicks
          t.timestamps
        end
      end
    end
    

    buttons_controller

    class ButtonsController < ApplicationController
      def index
        @button = Button.find(1)
      end
    
      def doit
        @button = Button.find(1)
        @newcount = @button.clicks + 1
        Button.find(1).update_attributes(:clicks => @newcount)
      end
    end
    

    Now.. i need to trigger the doit method.. is it possible to trigger a non CRUD operation ? i tried this but it doesn't seem to work index.html.erb

    <h1>Hello, This is button and my click are :</h1>
    <h1><%= @button.clicks %></h1>
    <%= link_to 'click me', method: :doit %>
    

    I know there's something I'm not getting here... Ruby have been doing so much magic that I can't do a simple ruby method.. it have been really hard for me getting the part were methods are taking place without calling them by name.. Specially when I trigger a delete method and the destroy method is triggered by that.. I really need to get used to this too-much-magic coding

    • Admin
      Admin about 12 years
      There doesn't appear to be any straightforward way to do that. Some people have written tools that let you do it; here's one of them. A Google search for "windows create shortcut command line" turns up some others. (I haven't tried any of them.)
    • Admin
      Admin about 12 years
      @iglvzx - I'm not sure that the editing you did is correct. I don't think that Shantanu needs a batch script - it could be any way of creating a *.lnk to another *.exe file.
    • Admin
      Admin over 6 years
      Use the following: powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Desktop\shortcu‌​t.lnk');$s.TargetPat‌​h='C:\Windows\';$s.S‌​ave()" Obviously, replace "'%userprofile%\Desktop\shortcut.lnk" and "C:\Windows\" with your shortcut path and target path, respectively.
    • Admin
      Admin over 6 years
      @cowlinator As typed, your suggestion does not work.
    • Admin
      Admin over 6 years
      @Ploni, it does work for me on my computer. What error message are you seeing? What is your powershell execution policy?
    • Admin
      Admin over 6 years
      @cowlinator Strange. Now it works for me too.
    • Admin
      Admin over 6 years
      That's good to hear, if a bit mystifying. If anybody else is having issues, you can try typing the following directly into powershell: $s=(New-Object -COM WScript.Shell).CreateShortcut($Env:userprofile + '\Desktop\shortcut.lnk');$s.TargetPath='C:\Windows\';$s.Save‌​()
    • Admin
      Admin over 6 years
      @cowlinator your comment contains multiple zero-width / non-printable characters. As you are asking users to copy and paste this into their command line, this can look quite bad from a security perspective. Please remove them and format your comment as raw string.
    • Admin
      Admin over 6 years
      For anyone interested, here is a cleaned version of @cowlinator's comment: powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Desktop\shortcu‌​t.lnk');$s.TargetPat‌​h='C:\Windows\';$s.S‌​ave()"
    • Admin
      Admin over 6 years
      @zsero, I was concerned about your comment, so I copy/pasted both of my above comments into notepad++ and selected "show all characters", but I found no non-printable characters. Also, I'd be pretty pretty surprised if stack-exchange sites didn't sanitize their inputs. What makes you believe there are non-printable characters there?
    • Admin
      Admin over 6 years
      @cowlinator in Chrome, right click: Inspect on your text to see it has 3 occurances of &zwnj;&#8203; in it.
  • Nir Alfasi
    Nir Alfasi about 12 years
    a shortcut is something you run from windows, since he used CMD in the title and put the tag "command-line" I assumed he wants to run it from CMD. A batch file is the equivalent of a windows "shortcut" when you run in CMD (dos like) env.
  • Keith Thompson
    Keith Thompson about 12 years
    Since he put "shortcut (.lnk file)" in the body of the question, I assumed he wants to create an actual shortcut.
  • Shantanu
    Shantanu about 12 years
    sorry for clarity i wanted to have a icon on my desktop that i made in cmd that would be a shortcut to a exe file
  • iglvzx
    iglvzx about 12 years
  • Nir Alfasi
    Nir Alfasi about 12 years
    now that I finally understood (slow thinker - what can you do...) I changed my answer. hope it helps!
  • Walter Stabosz
    Walter Stabosz about 10 years
    Good idea, but symlinks appear to behave a bit differently than shortcuts. If I create a shortcut to a Visual Studio solution, it opens all the relatively-pathed-projects correctly. However, if I open the same solution via a symlink, the working directory is that of the path in which the symlink resides, not the path to which it refers.
  • Nir Alfasi
    Nir Alfasi over 9 years
    @twasbrillig works for me...
  • EDM
    EDM about 8 years
    This works great for shortcut to a file. However, i'm having a weird problem using it for shortcut to a folder, when my variable Esc_LinkTarget contains an environment variable trying to get its parent folder. (Something like %CD%\.. does not work, but %CD% works). The shortcut target type becomes a 'File' instead of 'Folder'
  • Oliver Salzburg
    Oliver Salzburg about 8 years
    @Edmund Interesting problem. I don't have time to look into it, but I would assume a trailing slash could make a difference.
  • LPChip
    LPChip almost 8 years
    If this is the approach to take, it is better to create the actual shortcut (.lnk) which embeds the icon in it. That shortcut can then be copied everywhere.
  • Mahmoud Moustafa
    Mahmoud Moustafa over 7 years
    I had a problem with the only: [:index] syntax but once i switched it with only: :index the code worked. Now i know that i have to stick with the CRUD operations.. i can't just run a method randomly
  • Black
    Black almost 7 years
    Note: if you use SET Esc_LinkTarget=%0 then you have to remove the " from echo oLink.TargetPath = oWS.ExpandEnvironmentStrings^(!Esc_LinkTarget!^)
  • Scott - Слава Україні
    Scott - Слава Україні over 6 years
    Trix: If you believe that you have a better way of doing this, just post it as a new answer (linking to this one, if appropriate).
  • Sancarn
    Sancarn about 5 years
    Instead of creating a vbscript for each execution it would have been far better to use Wscript.Arguments to get the command line arguments... lol
  • GabrielBB
    GabrielBB almost 5 years
    Works like a charm. I liked the "Not complete snippet" more lol
  • Egon Stetmann.
    Egon Stetmann. almost 5 years
    thank you so much!!
  • Antares
    Antares about 4 years
    While I can understand the confusion, the question is about creating the "shortcut file" or "link file" (extension .lnk) of a shortcut itself. Your answer explains how to give an existing shortcut file a keyboard "shortcut". Your answer does not fit the question. But I will not downvote. It is well written and pictured and was given in good faith. I'd say it deserves an upvote just for the effort taken to compose it.
  • Antares
    Antares about 4 years
    Upvote given. At least, it does not deserve a negative score.
  • TamaMcGlinn
    TamaMcGlinn almost 4 years
    @Sancarn I have implemented that; also I didn't need to generate and then delete at all, in my case I can just leave the vbscript where it is. however, I am unfortunately unable to post my answer because someone marked this question as protected, and stackoverflow is for some arbitrary reason a separate site from superuser. :( unfortunate because the resulting solution is much simpler than all the others posted here.
  • Sancarn
    Sancarn almost 4 years
    @TamaMcGlinn Indeed, you can suggest edits to other people's answers, but protected threads are always a bit sad. I message to the mods might help getting it unlocked to post your answer :).
  • Hannes Schneidermayer
    Hannes Schneidermayer almost 4 years
    Very good nswer
  • user1696603
    user1696603 over 3 years
    With the Git I have (verison 2.27.0.windows.1) I had to dig to find this file as it wasn't referenced in PATH. Found in C:\Program Files\Git\mingw64\bin
  • Jimadine
    Jimadine over 3 years
    @mattwilkie The path to the exe is indicated in 'Example usage' above, with a note about PATH
  • user1696603
    user1696603 over 3 years
    Ahh, I see that now. I missed on first read because text field scrolled off right of screen (and my hasty reading).
  • loved.by.Jesus
    loved.by.Jesus over 3 years
    I am almost in tears: what a powerful piece of code!!! I have been trying to create a .lnk in WINE (Linux) to no avail. Your code did the job. I really appreciate that it uses the most basic tools .bat script and visual basic—no need of "power"shell. Thanks!
  • Tomas Tintera
    Tomas Tintera about 3 years
    Also creating simlink requires admin privilege.
  • Admin
    Admin almost 2 years
    Wouldn't it be more robust to check for where git.exe, then use that to determine the correct path of the create-shortcut.exe based on that? After all hardcoding paths isn't exactly the smartest idea. Even just using %ProgramFiles%\Git in place of C:\Program Files\Git would improve this quite a bit.
  • Admin
    Admin almost 2 years
    If you are scripting it, and are unsure of the environment i.e. where git might be installed to, yes, that would certainly be worthwhile. But the OP's question isn't about scripting the creation of shortcuts, nor is my answer.