PowerShell Create URL Shortcuts

  • Welcome to ITBible, we're your #1 resource for enterprise or homelab IT problems (or just a place to show off your stuff).
Just a quick script on creating URL Shortcuts, defaults to the Public user desktop and has support for custom icons.
param (
    [string]$IconPath = "C:\ITBible\Icons",
    [boolean]$Force = $false
# Create a new com object
$wshShell = New-Object -ComObject "WScript.Shell"

# set default path to public desktop
if (-not ($Path))
    $Path = $wshShell.SpecialFolders.Item("AllUsersDesktop")

# append \ to path if it does not exist
if ($Path -notmatch '\\$')
    $Path += "\"

# append \ to icon path if it does not exist
if ($IconPath -notmatch '\\$')
    $IconPath += "\"
$FullPath = Join-Path $Path "$($Name).url"
$FullIconPath = Join-Path $IconPath "$($Name).ico"

# If there is an icon make sure we can download it to the path and then download it
if ($IconUrl)
    if (-not (Test-Path -Path $IconPath))
        New-Item -ItemType Directory -Force -Path $IconPath
    Invoke-WebRequest -Uri $IconUrl -OutFile $FullIconPath

# verify the path exists or create it
if (-not (Test-Path -Path $Path))
    New-Item -ItemType Directory -Force -Path $Path

# Create the shortcut
$urlShortcut = $wshShell.CreateShortcut($FullPath)
$urlShortcut.TargetPath = $URL

if ($IconUrl)
    Add-Content -Path $FullPath -Value "IconFile=$($FullIconPath)"
    Add-Content -Path $FullPath -Value "IconIndex=0"

[System.Runtime.InteropServices.Marshal]::ReleaseComObject($urlShortcut) | Out-Null
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($wshShell) | Out-Null