Reading the Target of a Shortcut with Shell32 Interop
From IronPython Cookbook
Adapted from this C# example. (Which took a long time to find...)
Windows shortcut link files (.lnk) are odd creatures. They use a strange binary format documented here (pdf).
You can read them using Shell32 interoperability.
Run tlbimp. See Interop introduction for more information:
tlbimp %SystemRoot%\system32\shell32.dll /out:Interop.Shell32.dll
Or use ProgID "Shell.Application".
This generates a dll called 'Interop.Shell32.dll'. If we add the directory containing this dll to sys.path, then we can add a reference to it and import from it. Shell32 provides a lot of functionality, we are using ShellClass.
import sys
import clr
sys.path.append(PATH_TO_DIRECTORY_WITH_SHELL32_DLL)
clr.AddReferenceToFile('Interop.Shell32.dll')
from Interop.Shell32 import ShellClass
shell = ShellClass()
folder = shell.NameSpace(r"C:\Temp")
folderItem = folder.ParseName('filename.lnk')
link = folderItem.GetLink
path = link.Path
The code above can be rewritten as a function:
import clr
clr.AddReferenceToFile('Interop.Shell32.dll')
from System.IO import Path
from Interop.Shell32 import ShellClass
def GetLinkTarget(linkFilename):
shell = ShellClass()
folder = shell.NameSpace(Path.GetDirectoryName(linkFilename))
folderItem = folder.ParseName(Path.GetFileName(linkFilename))
return folderItem.GetLink.Path
The other side of the story is Creating a Shortcut File with WSH Interop.
There's lots in Shell32, functions for launching applications, managing printers and so on. There is an article (C#) on using it for reading ID3 tags from mp3 files here.
Back to Contents.

