Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I determine the executable file name corresponding to a .lnk shortcut file?

-- AM

SpacerHey, Scripting Guy! AnswerScript Center

Hey, DE. We’re glad you asked this question; unlike some questions we get (like, “How do I use a script to disable File and Print Sharing on my Windows 2000 computers?”), this happens to be one we have an answer for.

As it turns out, there’s a WMI class - Win32_ShortcutFile - that can retrieve this information for you. All you have to do is query the Win32_ShortcutFile class and ask for the Target property; that’s the name of the executable file (or script or document or whatever) that gets called when someone double-clicks the shortcut. Here’s a simple little script that lists all the shortcut files on a computer, specifying the icon caption that you see in My Computer or Windows Explorer (FileName), the name of the corresponding executable file (Target), and the file path to the shortcut itself (Description):

strComputer = "."
Set objWMIService = GetObject _
    ("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery("Select * From Win32_ShortcutFile")
For Each objFile in colFiles
    Wscript.Echo "Name: " & objFile.FileName
    Wscript.Echo "Shortcut target: " & objFile.Target
    Wscript.Echo "File name: " & objFile.Description
Next

Of course, you don’t have to wade through all the shortcuts on a computer. Suppose you just want to locate the executable file for a single shortcut. In that case, you could use a script similar to this:

strComputer = "."
Set objWMIService = GetObject _
    ("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
    ("Select * From Win32_ShortcutFile WHERE FileName = 'Adobe Photoshop Elements 2.0'")
For Each objFile in colFiles
    Wscript.Echo "Name: " & objFile.FileName
    Wscript.Echo "Shortcut target: " & objFile.Target
    Wscript.Echo "File name: " & objFile.Description
Next

Here’s another example, which checks to see if there are any shortcuts on a computer that reference Microsoft Virtual PC. Note that - per WMI conventions - any time you use a file path in a query you must use two \\’s in path names rather than one:

strComputer = "."
Set objWMIService = GetObject _
    ("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
    ("Select * From Win32_ShortcutFile WHERE Target = " & _
        "'C:\\Program Files\\Microsoft Virtual PC\\Virtual PC.exe'")
For Each objFile in colFiles
    Wscript.Echo "Name: " & objFile.FileName
    Wscript.Echo "Shortcut target: " & objFile.Target
    Wscript.Echo "File name: " & objFile.Description
Next

That should give you a headstart on retrieving information about shortcuts. For those of you who’ve asked about creating and deleting shortcuts, we’ll address those topics very soon.