How to create a shortcut to a folder on Windows?

4.8k Views Asked by At

I have created shortcuts for executables and it works, but when I try to create one for a folder it does not work. It does create a shortcut, it is just not the right 'Target Type'. Please take a look at the image below. Instead of 'File', the target type should be 'File folder'. The problem is that when I open the shortcut it asks me which program do I want to open the File with and it does not open the folder.

screenshot showing incorrect Target property of a shortcut created to a folder with my code

The function I'm using to create the shortcuts is the following

from win32com.client import Dispatch
import winshell
import os

def create_shortcuts(self, tool_name, exe_path, startin, icon_path):

    shell = Dispatch('WScript.Shell')
    shortcut_file = os.path.join(winshell.desktop(), tool_name + '.lnk')
    shortcut = shell.CreateShortCut(shortcut_file)
    shortcut.Targetpath = exe_path
    shortcut.WorkingDirectory = startin
    shortcut.IconLocation = icon_path
    shortcut.save()

I don't know if it's possible to set the 'Target Type'. I couldn't find a way to do it, but I do know there must be a way.

2

There are 2 best solutions below

0
On

For future reference: I observed the described behavior in python 3.9.6 when creating a shortcut to a non-existing directory, which was easily fixed by incorporating os.makedirs() into the method. I've added a method parameter to the version I'm using, so it can handle shortcuts to files and directories:

def create_shortcuts(self, tool_name, exe_path, startin, icon_path, is_directory=False):
    if is_directory:
        os.makedirs(exe_path, exist_ok=True) 

    shell = Dispatch('WScript.Shell')
    shortcut_file = os.path.join(winshell.desktop(), tool_name + '.lnk')
    shortcut = shell.CreateShortCut(shortcut_file)
    shortcut.Targetpath = exe_path
    shortcut.WorkingDirectory = startin
    shortcut.IconLocation = icon_path
    shortcut.save()
0
On

If you want to use .Net "clr" (especially if you already require it):

First run this... you will have to ship the output of this command with your application:

"c:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\TlbImp.exe" %SystemRoot%\system32\wshom.ocx /out:Interop.IWshRuntimeLibrary.dll

tlbimp.exe might even be in the path if you installed the Windows SDK in a fairly standard way. But if not, it's OK, you'll just ship the "assembly" (fancy word for interface-providing dll in .Net land) with your application.

Then this code will work in python:

import clr
sys.path.append(DIRECTORY_WHERE_YOU_PUT_THE_DLL)
clr.AddReference('Interop.IWshRuntimeLibrary')
import Interop.IWshRuntimeLibrary
sc = Interop.IWshRuntimeLibrary.WshShell().CreateShortcut("c:\\test\\sc.lnk")
isc = Interop.IWshRuntimeLibrary.IWshShortcut(sc)
isc.set_TargetPath("C:\\")
isc.Save()

.... the above code, with far too much modification and preamble, might even work with Mono.