How can I change icons for existing URL shortcuts

2019-03-01 21:56发布

问题:

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)

回答1:

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()


回答2:

I was writing a script to change the default folder icon to the icon of a Network drive. This might help somewhere. The command is:

$ShortCut.IconLocation = "C:\WINDOWS\system32\imageres.dll, 28";



回答3:

for me .iconlocation does not exist in $shortcut and gives an error (might be the powershell version...). but here is how changed the url icon to a custom one i made: (the main part is the add-content commands)

$WshShell = New-Object -comObject WScript.Shell

$path = "C:\Users\USER\desktop\WEBSITE.url"

$targetpath = "https://WEBSITE.com"

$iconlocation = "C:\Users\USER\Desktop\YourIcon.ico"

$iconfile = "IconFile=" + $iconlocation

$Shortcut = $WshShell.CreateShortcut($path)

$Shortcut.TargetPath = $targetpath

$Shortcut.Save()

Add-Content $path "HotKey=0"

Add-Content $path "$iconfile"

Add-Content $path "IconIndex=0"