0

Following snippet shows how to extract the target of a shortcut in Windows:

import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
fp = r'C:\very_long_path\to\a\link\file\shortcut.lnk'
shortcut = shell.CreateShortCut(fp)
#targetPath = "\\\\?\\"+shortcut.Targetpath # Does not help
targetPath = shortcut.Targetpath

The code above fails if the lnk file is on a too long path. How can I get the shortcut's target path in this case?

user2366975
  • 4,350
  • 9
  • 47
  • 87
  • I'm afraid you'll have to work around it: http://social.technet.microsoft.com/Forums/en-US/ITCG/thread/874d303f-f201-4fee-ad47-4f7c8979434f/#c21fb909-939a-440d-85a6-60cc6d09cc45 – CristiFati Jan 25 '18 at 15:45

1 Answers1

0

I believe the limitations you are facing are within the win32com.client.Dispatch("WScript.Shell") this is why you are facing the 260 character limitation and the prefixing with \\?\ is not solving your problem.

You will have to work around it by

  • copying folder to a shorter path (the copying can be done with \\?\ prefix to avoid limitation of path length)
  • then create the shortcut (without \\?\ prefix), but with the longer path target.
  • and copy all back (again with \\?\ prefix).

Alternatively you can consider using a Symbolic Link in stead of a Shortcut (Windows Vista and higher) which can be created with os.symlink() and this will work with \\?\ prefix for long path names. This is what I personally have done multiple times, as it is just simpler to implement. But you will have to ask the question if this "shortcut" or "symlink" is really needed, as once you have a "symlink" you do need to delete both source as symlink upon delete, else your file will remain.

Lastly you can do this the hard way: recreate code to create a shortcut file in the correct format. Here is some Microsoft Documentation, a search online will reveal multiple links with useful information.

Although I do not have experience with this, there seems to be a module which claims it can natively create .lnk files

Edwin van Mierlo
  • 2,398
  • 1
  • 10
  • 19
  • Thanks for your answer. To clarify: I only want to extract the links's target, and do not want to create a new .lnk shortcut file. This task is part of a folder file analysis workflow. I will try later if this works. – user2366975 Jan 26 '18 at 12:11