[Source: http://geekswithblogs.net/EltonStoneman]
Windows shortcuts are .LNK files – a proprietary binary format which is not simple to generate. If you want to create shortcuts as part of an MSBuild deployment, the main issue is that the paths are not relative, they need to be explicit, so you can't create your own shortcuts and copy them. Alternatives are to create .URL or batch files containing relative paths, but they don't have the niceties of shortcuts.
You can generate .LNK shortcuts in MSBuild by shelling out to some VBScript at runtime, when you've deployed your files and know the exact paths. It's not a pretty solution, but it's fast and reliable. Create a .VBS file with the following content to generate a shortcut from given parameters:
'CreateShortcut.vbs
'Generates a .LNK shortcut to the specified program
'Usage: CreateShortcut.vbs <pathToExe> <exeName> <shortcutName>
Dim args, arg
Set args = WScript.Arguments
Dim workingDirectory, exeName, shortcutName
workingDirectory=args(0)
exeName=args(1)
shortcutName=args(2)
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
Dim objLink
Set objLink = WshShell.CreateShortcut("Shortcuts\" & shortcutName & ".lnk")
objLink.Description = shortcutName
objLink.TargetPath = workingDirectory & "\" & exeName
objLink.WindowStyle = 1
objLink.WorkingDirectory = workingDirectory
objLink.Save
Then call it from MSBuild after you've deployed the target file and know the path:
<Exec Command='CreateShortcut.vbs """$(AppDir)""" AppName.exe AppFriendlyName.exe'/>
Points to note:
- If you have any spaces in the arguments (C:\Program Files\etc) you need to wrap them in triple double-quotes ("""C:\Program Files\etc"""), otherwise each word is parsed as a separate argument in VBScript;
- The friendly name of the shortcut can end in any extension – Windows hides the final .LNK , so if you specify a .EXE it will display as an EXE;
- Shortcuts aren't limited to executables, if you pass a Word file as the exeName argument and end the shortcutName with .DOC, it'll launch the document in Word and show it with the Word icon in Explorer;
- You have a lot of control over the link from the CreateShortcut call – including the startup window type, arguments and the icon. The example above is a straightforward one which just sets the minimum necessary.