AnonymousKraken
AnonymousKraken

Reputation: 31

Extract icon from shortcut (.lnk) file in Python?

I'm trying to extract the icons from all of the shortcuts in the Start Menu folder. So far I've managed to walk the directory tree, and I just need something to extract the icon from each shortcut. I've tried a few methods suggested across the internet, but I can't seem to make it work fully.

Method 1: Using a program called ResourcesExtract through os.system() to extract the icon from the .lnk file. I soon discovered that this doesn't work for .lnk files, only .exe or .dlls.

import os

os.system(f"resourcesextract.exe /source {shortcut}")

Method 2: Extracting the icon file from the targets of the shortcuts (which can be obtained quite easily using the pywin32 library) using ResourcesExtract. Unfortunately, this only works for some of the programs, due to some shortcuts pointing to .exes without icons.

import os
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")

target = shell.CreateShortCut(shortcut).TargetPath
os.system(f"resourcesextract.exe /source {target}")

Method 3: Using pywin32 to get the icon directory. This only works for around 120 of the 300 shortcuts I need it to work on.

import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")

icon, status = str(shell.CreateShortCut(shortcut).IconLocation).split(",")

I also came across a way to do it using the .NET framework, but I don't know how to interface that with python or if it will even work.


Is anyone aware of a method to extract icons from .lnk files in Python that works on all shortcuts?

Upvotes: 3

Views: 1544

Answers (1)

fly doz
fly doz

Reputation: 11

import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
ShortCut = shell.CreateShortCut('example.lnk')
icon_location = ShortCut.IconLocation

It work for me.

Upvotes: 1

Related Questions