mreff555
mreff555

Reputation: 1133

Creating a directory shortcut in powershell

I'm writing my first powershell script and I'm having a little trouble.

Up to this point my system creates a directory tree and populates it with files. The final step is to put a shortcut on my desktop.

I've come up with the code below:

$ShortcutFile = "$home\Desktop\" + $protocol + ".lnk"
If ( (test-path -path "$ShortcutFile") -ne $true)
{
    $WScriptShell = New-Object -ComObject WScript.Shell
    $Shortcut = $WScriptShell.CreateShortcut($ShortcutFile)
    $Shortcut.TargetPath = $root_path
    $Shortcut.Save()
}

This doesn't work as I'm sure any experienced powershell user knows. A file is created rather than a directory. I imagine the correct way to fix this is to change one of the object members in WScript.Shell which control's the file type. I have had no luck locating any resources on how to do this specifically, or any other way to go about doing it. I found the API on the MSDN website but there where only a few members listed. There must be more. What is the best way to accomplish this?

Thanks

Upvotes: 5

Views: 13369

Answers (3)

Bulgypayload
Bulgypayload

Reputation: 51

New-Item -itemtype symboliclink -Path "PathWhereYouWantToPutShortcut" -name "NameOfShortcut" -value "PathOfWhatYourTryingToLinkTo"

New-Item Documentation

Upvotes: 5

Philip Busse
Philip Busse

Reputation: 1

I experienced this when creating a shortcut to a directory that didn't exist. If I simply created the directory ahead of time, then the shortcut worked correctly.

Upvotes: 0

kalebo
kalebo

Reputation: 372

Assuming that you mean the shortcut type is a File rather than a File folder then a workaround is to make an Application launcher instead, which always works.

I originally found this solution here.

    $wsshell = New-Object -ComObject WScript.Shell
    $lnk = $wsshell.CreateShortcut($ShortcutFile)
    $lnk.WindowStyle = 1
    $lnk.TargetPath = "explorer.exe"
    $lnk.Arguments = $TargetPath
    $lnk.IconLocation = "explorer.exe,0"
    $lnk.save() # This will overwrite the previous link if it existed

Upvotes: 4

Related Questions