powershellshortcut-file

Change icon for file from PowerShell


I am trying to create the URL file with a custom icon but, for some reason, it is not working. This is my code:

#Downloading ico file
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile("url location of the icon file","C:\Users\Public\Pictures\filename.ico")

#Creating URL file
$wshShell = New-Object -ComObject "WScript.Shell"
$urlShortcut = $wshShell.CreateShortcut(
  (Join-Path $wshShell.SpecialFolders.Item("AllUsersDesktop") "myname.url")
)
$urlShortcut.TargetPath = "https://somewebsite"
$urlShortcut.IconLocation = "C:\Users\Public\Pictures\filename.ico"
$urlShortcut.Save()

The icon file is downloaded, and the URL file is created but, the image is not changed. I've tried a few different things with no luck.

Would be nice if anyone has some input on this.

Kind regards,


Solution

  • The .IconLocation property isn't supported in your case, but there's a workaround:

    # ... icon download code omitted
    
    $shortcutFile = Join-Path $wshShell.SpecialFolders.Item('AllUsersDesktop') 'myname.url'
    $iconFile = 'C:\Users\Public\Pictures\filename.ico'
    
    $wshShell = New-Object -ComObject "WScript.Shell"
    $urlShortcut = $wshShell.CreateShortcut($shortcutFile)
    $urlShortcut.TargetPath = 'https://en.wikipedia.org'
    $urlShortcut.Save()
    
    # This updates the .url file directly to emulate what assigning 
    # an icon interactively, via File Explorer, does.
    @"
    IconIndex=0
    HotKey=0
    IconFile=$iconFile
    "@ | Add-Content -LiteralPath $shortcutFile
    

    When you create a URL shortcut file (extension .url):

    However, the .url file format does support custom icons (by default, the default browser's icon is used), but that requires assigning them interactively, via File Explorer.

    Fortunately, .url files are plain-text, .ini-like files, so it's easy to programmatically update that file directly, so as to emulate the results of interactively assigning an icon, as shown above.


    Alternatively - which may or may not be an option in your case - you can create a regular shortcut file, with extension .lnk, which - perhaps surprisingly - also works with URLs assigned to .TargetPath. Assigning to .IconLocation then works as usual.
    However, there are ramifications: