Thursday, September 12, 2019

Creating a shortcut with PowerShell

I was asked once again, "How can I use PowerShell to create a shortcut?". For those who may have been scripting for a bit, we used to have a nifty VBScript to complete this task. It was something similar to this:

Set objShell = WScript.CreateObject("WScript.Shell")
Set lnk = objShell.CreateShortcut("C:\MyShortcut.LNK")

lnk.TargetPath = "C:\Program Files\MyApp\MyProgram.EXE"
lnk.Arguments = ""
lnk.Description = "MyProgram"
lnk.HotKey = "ALT+CTRL+F"
lnk.IconLocation = "C:\Program Files\MyApp\MyProgram.EXE, 2"
lnk.WindowStyle = "1"
lnk.WorkingDirectory = "C:\Program Files\MyApp"
lnk.Save

PowerShell is a newer method to complete these tasks. As you may know, it has the ability to handle calls to the Windows Scripting Host and generally ease execution as you don't need to call the scripting host for processing. Translation, no batch file to execute the VBScript using the desired scripting engine. Below is an example:

$Shell = New-Object -ComObject ("WScript.Shell") #Set the shell used
$ShortCut = $Shell.CreateShortcut($env:USERPROFILE + "\Desktop\Whatever.lnk") #Where to create the shortcut
$ShortCut.TargetPath="executable.exe" #Set the path and file name for the target
$ShortCut.Arguments="-arguementsifrequired" #Only if necessary
$ShortCut.WorkingDirectory = "path to file"; #Remember, apps need to know where they started from
$ShortCut.WindowStyle = 1; # 1 - Activates and displays a window.3 - Activates the window and displays it as a maximized window.7 - Minimizes the window and activates the next top-level window.
$ShortCut.Hotkey = "CTRL+SHIFT+F";
$ShortCut.IconLocation = "yourexecutable.exe, 0"; #Picture for shortcut and index number from file
$ShortCut.Description = "Your Custom Shortcut Description"; #What is it
$ShortCut.Save() #Create the shortcut

You can also create a shortcut to a URL. Not much different, but here is an example:

$Shell = New-Object -ComObject ("WScript.Shell")
$URL= $Shell.CreateShortcut($env:USERPROFILE + "\Desktop\Whatever.url")
$URL.TargetPath = "http://www.url.com";
$URL.Save()

You still call the Windows Script host to complete the work. However, the file name is '.url' rather than '.lnk', which invokes the browser as it is a known file type association. This is a quick post, for more detail on these examples be sure to check out the following:

https://ss64.com/vb/shortcut.html
http://powershellpainrelief.blogspot.com/2013/03/creating-desktop-shortcuts-using.html

Now you are able to incorporate this in your deployment scripts via your chosen tools or by simply executing your script!

-Happy Scripting!