Skip to content

Instantly share code, notes, and snippets.

@Winand
Created February 21, 2017 07:41
Show Gist options
  • Save Winand/997ed38269e899eb561991a0c663fa49 to your computer and use it in GitHub Desktop.
Save Winand/997ed38269e899eb561991a0c663fa49 to your computer and use it in GitHub Desktop.
@hannesdelbeke
Copy link

hannesdelbeke commented Dec 14, 2022

better performance for multiple shortcuts, running everything in 1 powershell cmd.
get all links, recursively in a folder

nearly instant instead of wait a few seconds when running on all shortcuts in windows start menu

def get_target_and_args_folder(folder) -> (str, str):
    """
    Get the target & args of all Windows shortcuts (.lnk) in a folder
    :param link_path: The Path or string-path to the shortcut, e.g. "C:\\Users\\Public\\Desktop\\My Shortcut.lnk"
    :return: A tuple of the target and arguments, e.g. ("C:\\Program Files\\My Program.exe", "--my-arg")
    """
    # see https://gist.github.com/Winand/997ed38269e899eb561991a0c663fa49

    ps_command = \
        "$Shortcuts = Get-ChildItem -Recurse \"" + str(folder) + "\" -Include *.lnk;" \
        "$WSShell = New-Object -ComObject Wscript.Shell;" \
        "foreach ($ShortcutPath in $Shortcuts)" \
        "{" \
        "$Shortcut = $WSShell.CreateShortcut($ShortcutPath);" \
        "Write-Host $Shortcut.TargetPath ';' $shortcut.Arguments " \
        "}"
    output = subprocess.run(["powershell.exe", ps_command], capture_output=True)
    raw = output.stdout.decode('utf-8')

    result = []
    for line in raw.splitlines():
        launch_path, args = [x.strip() for x in line.split(';', 1)]
        result.append((launch_path, args))
    return result

@Winand
Copy link
Author

Winand commented Dec 14, 2022

@hannesdelbeke yes, it's very basic implementation which does not work with some .lnk files.
So I switched to ShellLink.GetPath COM method. You just create IShellLink() object and call get_path(path_to_link).

see also IShellLink docs

@hannesdelbeke
Copy link

Thanks for the update!
if i'm not mistaken, the python implementation for that uses win32com, which is not in the standard python library.

@Winand
Copy link
Author

Winand commented Dec 14, 2022

Thanks for the update! if i'm not mistaken, the python implementation for that uses win32com, which is not in the standard python library.

No no, com_interfaces is a package i've made recently. It uses only ctypes. I've added IShellLink as an example. You can implement other interfaces in a similar way (using Microsoft docs, etc.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment