A couple weeks ago, I wrote about some scripts we use at work for creating shortcuts to various programs in Windows. Well, we also push out updates to some programs which change the paths of the programs and then we need to change the user’s shortcuts to match. Unfortunately, some user’s will change the name of the shortcut which can make finding it difficult. Python makes it easy to find the shortcut I need to change though and in this article I’ll show you how to do it.
import glob import win32com.client import winshell paths = glob.glob(winshell.desktop() + "\\*.lnk") shell = win32com.client.Dispatch("WScript.Shell") old_program_path = r"\\SomeUNC\path\old.exe" # find the old links and change their target to the new executable for path in paths: shortcut = shell.CreateShortCut(path) target = shortcut.Targetpath if target == old_program_path: shortcut.Targetpath = r"\\newUNC\path\new.exe" shortcut.save()
First, we import glob, win32com.client and winshell, then we create a list of paths where the shortcuts that we need to change will be. In this case, we look at just the user’s desktop, but you can modify it to include other directories (like Start Up). Then we create a shell object and set up a variable to hold the old program’s link path that we want to find.
Finally, we loop over the link paths and use the shell object to peek into the shortcut’s properties. The only property we care about is the shortcut’s Target, so we grab that and use the conditional to check if it’s the right one. If it’s not, then we continue to loop to the next link. If it is the right one, then we change the Target to point to the new location.
Fortunately, this doesn’t happen very often; but when it does, you’ll know that Python has your back.