How can I change icons for existing URL shortcuts using Powershell?

Rincewind picture Rincewind · Jan 17, 2017 · Viewed 18.9k times · Source

I am wanting to change the icon for an existing shortcut using Powershell.

I played around with it but I couldn't set the changes so I went online and came up empty-handed. I've seen examples with VB and Command Shell but nothing with Powershell. Nearly 99% demonstrated how to create the shortcut but I just need to know how to change the icon and only the icon.

Here is what I did so far:

# Make a copy of the icon in the directory
PS> cd Program Files (x86)\Dir\Fol\
PS Program Files (x86)\Dir\Fol> cp 1234567890.ico 12345678901.ico

# Gets the IconFile property and changes it to the new icon
PS Program Files (x86)\Dir\Fol> cd Desktop\Folder\
PS Desktop\Folder>(Get-Content "file name")[6]
IconFile=C:\Program Files (x86)\Dir\Fol\1234567890.ico
PS Desktop\Folder>(Get-Content "file name")[6] -replace ".ico","1.ico"

I've tried working with the WScript.Shell ComObject but that seems to only create new shortcuts.

I feel like where I was going with it would work if there was a way to save, update, and apply the new IconFile path in the object.

I'm doing this as a fix action due to icons (or maybe something in the symbolic LNK?) "breaking" and defaulting to a generic icon. Seems to only be an issue with shortcuts. The shortcut works perfectly, everything is fine but for one reason or another, the icons default. If I go in and reapply the same icon name through the GUI, it won't change. However, if I change the name of the .ico file by any measure and then set it, it works. Don't know why it is doing it but I was wanting to create a PS script that would do it automatically (and I was looking for an excuse to jam out a script)

Answer

BenH picture BenH · Jan 17, 2017

The wscript.shell CreateShortcut method will create a new OR open an existing shortcut. Here's a short script, where you will need to define $ShortcutPath, $IconLocation, and $IconArrayIndex:

$Shell = New-Object -ComObject ("WScript.Shell")
$Shortcut = $Shell.CreateShortcut($ShortcutPath)
$Shortcut.IconLocation = "$IconLocation, $IconArrayIndex"
$Shortcut.Save()