Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get target of shortcut (.lnk) file with powershell

Tags:

I have a bunch of .lnk files and need to treat them differently depending on the target that the shortcut points to. I've found very little of how to this with other languages, but nothing about doing this with powershell.

I've tried this:

$sh = New-Object -COM WScript.Shell
$target = $sh.CreateShortcut('<path>').Target

But this returns an empty string even though I can see in the .lnk properties that the Target is specified.

Any idea on how to accomplish this?

like image 584
Mythio Avatar asked Mar 13 '17 11:03

Mythio


People also ask

How do you find the location of a .LNK file?

Windows generated LNK files are stored in the folder C:\Users\ <username>\AppData\Roaming\Microsoft\Windows\Recent.

How do I open a .LNK file in Powershell?

Open powershell.exe , cd to shortcut directory, run . \lnkping 1.1. 1.1 - invocation immediately returns, new conhost window is open and output is displayed there.

How do you read a .LNK file?

How to open an LNK file. Opening an LNK file, by double-clicking it or right-clicking it and selecting Open, opens the file, folder, or program to which the LNK file points. Advanced users can edit an LNK file's properties by right-clicking the file and selecting Properties.

What is TargetPath in powershell?

@HelloWorldIsMyMotto Nope.. the TargetPath is the path to the executable (i.e. powershell.exe). The Arguments then hold the parameters to send to this executable.


1 Answers

You have made an error in the property; as wOxxOm suggests, you should be using TargetPath rather than Target:

$sh = New-Object -ComObject WScript.Shell
$target = $sh.CreateShortcut('<full-path-to-shortcut>').TargetPath

Google and MSDN were indeed helpful here; additionally, piping objects to Get-Member can often be useful and educational. This question also shows how to manipulate shortcuts using PowerShell, and uses the same technique as seen here.

If you want the arguments to the executable as well, those are stored separately:

$arguments = $sh.CreateShortcut('<full-path-to-shortcut>').Arguments

Again, piping objects to Get-Member - in this case, the object returned by WScript.Shell.CreateShortcut() - provides useful information.

like image 155
Jeff Zeitlin Avatar answered Sep 22 '22 03:09

Jeff Zeitlin