locked
How to get a shortcut name and target path from an existing LNK file RRS feed

  • Question

  • Hi,

    I need to do a search on a computer for a specific shortcut. There is a 'word' that will always be the same in the name of the link file so wildcards can be used but the actual name could have other letters or numbers in the name which cannot be predicted. I can find the existence of the file using wildcards with Test-Path but it would be useful if I could get the actual name of the link file. Testing if the file exists is not difficult and it does tell me if the link is found or not:

    $path = Test-Path "C:\Users\Public\Desktop\*MyFile*.lnk"

    How would you go about getting the actual name that is used for the link when wildcards are used? I have tried this:

    $wsh = New-Object -ComObject WScript.Shell
    $target = $wsh.CreateShortcut('C:\Users\Public\Desktop\*MyFile*.lnk').TargetPath
    $link = $wsh.CreateShortcut('C:\Users\Public\Desktop\*MyFile*.lnk').FullName

    $target $link


    The line for target path works if you know the actual name of the shortcut but returns nothing when wildcards are used. For the FullName property, it seems to just repeat the path I used in the line, i.e. C:\Users\Public\Desktop\*MyFile*.lnk. The wildcards are not resolved into the actual name.

    Is this possible? I've done a few searches but I am not seeing an example of anyone trying to do this.

    Thank you!

    Rob

    Monday, November 4, 2019 9:37 PM

Answers

  • Use Get-ChildItem to retrieve a reference to the file(s) using the wildcards, ForEach-Object to get a reference to each one, and then use CreateShortcut to open the shortcut.

    -- Bill Stewart [Bill_Stewart]


    • Edited by Bill_Stewart Monday, November 4, 2019 9:47 PM
    • Proposed as answer by jrv Monday, November 4, 2019 9:56 PM
    • Marked as answer by robwm1 Monday, November 4, 2019 10:56 PM
    Monday, November 4, 2019 9:47 PM

All replies

  • Use Get-ChildItem to retrieve a reference to the file(s) using the wildcards, ForEach-Object to get a reference to each one, and then use CreateShortcut to open the shortcut.

    -- Bill Stewart [Bill_Stewart]


    • Edited by Bill_Stewart Monday, November 4, 2019 9:47 PM
    • Proposed as answer by jrv Monday, November 4, 2019 9:56 PM
    • Marked as answer by robwm1 Monday, November 4, 2019 10:56 PM
    Monday, November 4, 2019 9:47 PM
  • That makes sense. Trying it out now.

    Updated:

    Your suggestion was pretty simple to implement.

    $links = Get-ChildItem -Path C:\Users\Public\Desktop -Name *MyFile*.lnk
    
    foreach($link in $links) {
        $wsh = New-Object -ComObject WScript.Shell
        $target = $wsh.CreateShortcut("C:\Users\Public\Desktop\$link").TargetPath
    }
    
    $target

    Thanks for the hint!

    -Rob



    • Edited by robwm1 Monday, November 4, 2019 11:27 PM
    Monday, November 4, 2019 9:53 PM