Creating a Shortcut File with WSH Interop

From IronPython Cookbook

Windows shortcut link files (.lnk) are odd creatures. They use a strange binary format documented here (pdf).

Run tlbimp. See Interop introduction for more information:

tlbimp %SystemRoot%\system32\wshom.ocx /out:Interop.IWshRuntimeLibrary.dll

Or use ProgID "WScript.Shell".

Here is the documentation for the Windows Scripting Host Objects (warning: dumb IE only website).

We can then add a reference to the dll and use WshClass to create new shortcuts:

import clr
import sys

from Interop.IWshRuntimeLibrary import WshShellClass

shortcut = WshShellClass().CreateShortcut('c:\\Test\\SomeFile.lnk')
shortcut.TargetPath = targetPathName

This uses the WshShell Class to create a WshShortcut. (Warning: Same dumb IE only site I'm afraid.)

The WshShorcut has lots of interesting properties that you can set.

shell = WshShellClass()
shortcut = shell.CreateShortcut('c:\\Test\\SomeFile.lnk')
shortcut .TargetPath = targetPathName
shortcut.WindowStyle = 1
shortcut.Hotkey = "CTRL+SHIFT+F"
shortcut.IconLocation = "notepad.exe, 0"
shortcut.Description = "Shortcut Script"
shortcut.WorkingDirectory = "c:\\Temp"

Bizarrely, you can't use this interface for examining an existing link - you need to use Shell32 interop instead...

See Reading the Target of a Shortcut with Shell32 Interop.

For yet another way to create a shortcut with Ironpython. This time, using the PreferComDispatch feature of IronPython 2.0 B1.

from System import Type, Activator
wb = Activator.CreateInstance(Type.GetTypeFromProgID("WScript.Shell"))
Desktop = wb.SpecialFolders("Desktop")
ShellLink = wb.CreateShortcut(Desktop + "\Notepad.lnk")
ShellLink.TargetPath = "notepad.exe"
ShellLink.WindowStyle = 1
ShellLink.Hotkey = "CTRL+SHIFT+F"
ShellLink.IconLocation = "notepad.exe, 0"
ShellLink.Description = "Shortcut Script"
ShellLink.WorkingDirectory = Desktop

Run this with the -X:PreferComDispatch option for this to work. Note this feature is planned to be enabled by default.

Back to Contents.