How to create a shortcut on the desktop with PowerShell

3

1

I have been referring to answer number three of this post to write my PowerShell script, but it doesn't appear to be working.


$linkPath        = Join-Path ([Environment]::GetFolderPath("Desktop")) "My shortcut.lnk"
$targetPath      = Join-Path ([Environment]::GetFolderPath("MyDocuments")) "...\run.exe"
$link            = (New-Object -ComObject WScript.Shell).CreateShortcut($linkPath)
$link.TargetPath = $targetPath

It only prints out the code in the output pane but never seems to fully execute; no shortcut shows up on the desktop.

Rob

Posted 2012-01-01T14:52:29.483

Reputation: 616

Sorry, but it is better to edit the answer instead of editing original question. When I first read that, I did not understand your question, that is already solved, so the answer was unnecessary. So I saw on question edits what really happened. – kokbira – 2015-08-31T17:51:59.810

Answers

5

You need to call the Save method of the shortcut object to actually store the shortcut as a file.

$linkPath        = Join-Path ([Environment]::GetFolderPath("Desktop")) "My shortcut.lnk"
$targetPath      = Join-Path ([Environment]::GetFolderPath("MyDocuments")) "...\run.exe"
$link            = (New-Object -ComObject WScript.Shell).CreateShortcut($linkPath)
$link.TargetPath = $targetPath

$link.Save()

See also:

user1686

Posted 2012-01-01T14:52:29.483

Reputation: 283 655

1

If you want to automate it and create shortcuts whenever you want, here's a script that may help you to do that.

The script will work like an app waiting for you enter the data user and remote pc name, in lines under the #example you'll need to replace everything inside the [] to your needs, you can also (and I recommend that) duplicate #example lines to create multiple shortcuts at once.

$ErrorActionPreference = "SilentlyContinue"

  function shortcut
{
    param
  ( 
    $DestinationPath,   
    $source,
    $icon
  )

  # CODE

  $WshShell = New-Object -ComObject WScript.shell
  $shortcut = $WshShell.CreateShortcut($DestinationPath)
  $shortcut.TargetPath = $Source
  $shortcut.iconlocation = $Icon
  $Shortcut.Save() 
}

$DestinationPath = read-host "Host"
$User = read-host "User"

#Example

shortcut "\\$DestinationPath\c$\users\$user\desktop\[your shortcut.lnk]" "[source for your shortcut]" "[icon path if needed]"    

if(Test-Path "\\$DestinationPath\c$\users\$user\desktop\[your shortcut.lnk]")
{Write-host "`nShortcut created: [your shortcut]`nHost:$DestinationPath`nUser:$user`n" -ForegroundColor Green}

else{write-host "Shortcut couldn't be created in $DestinationPath"}

Felipe Santos

Posted 2012-01-01T14:52:29.483

Reputation: 11