How to create a shortcut on the desktop with PowerShell
13,251
Solution 1
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:
- All code examples in the question you are referring to
- KB 244677 How to create a desktop shortcut with the Windows Script Host
- Microsoft Windows 2000 Scripting Guide. Working with Shortcuts
Solution 2
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"}
Related videos on Youtube
Author by
Rob
Updated on September 18, 2022Comments
-
Rob over 1 year
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.
-
kokbira over 8 yearsSorry, 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.
-