powershell - 从 PowerShell 更改文件的图标

标签 powershell shortcut-file

我正在尝试使用自定义图标创建 URL 文件,但由于某种原因,它不起作用。 这是我的代码:

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

图标文件已下载,URL 文件已创建,但图像未更改。我尝试了一些不同的方法,但没有成功。

如果有人对此有任何意见,那就太好了。

亲切的问候,

最佳答案

您的情况不支持 .IconLocation 属性,但有一个解决方法:

# ... 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

当您创建URL快捷方式文件(扩展名.url)时:

  • 结果 WshUrlShortcut 仅支持一个可写属性对象,即TargetPath,存储目标URL。

  • 值得注意的是,这会阻止使用 IconLocation 属性,该属性仅适用于可执行快捷方式文件(扩展名 .lnk) ,分别是WshShortcut对象。

但是,.url 文件格式确实支持自定义图标(默认情况下,使用默认浏览器的图标),但这需要以交互方式分配它们/em>,通过文件资源管理器。

幸运的是,.url 文件是类似 .ini 的纯文本文件,因此很容易以编程方式直接更新该文件,从而模拟以下结果以交互方式分配图标,如上所示。


或者 - 在您的情况下,这可能是也可能不是一个选项 - 您可以创建一个常规快捷方式文件,扩展名为 .lnk,这 - 也许令人惊讶 - 也适用于分配给 .TargetPath 的 URL。然后分配给 .IconLocation 即可正常工作。
然而,也有一些后果:

  • 显然,您最终会得到不同的文件扩展名,并且快捷方式文件将无法通过其扩展名轻松识别为 URL 快捷方式。

  • .lnk 文件是二进制 文件。

  • .lnkURL 作为目标路径的文件莫名其妙地不允许稍后通过文件资源管理器编辑该 URL。

关于powershell - 从 PowerShell 更改文件的图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71768886/

相关文章:

powershell - 无法在 Powershell 中使用带有管道变量的 -filter 子句运行 Get-CASMailbox

PowerShell 提供程序相对路径制表符完成问题

powershell - 在 if block 中无法识别 $Env 变量

eclipse - 如何创建 MyEclipse 快捷方式来打开多个工作区?

windows - 安装到特定用户文件夹更改为安装到当前用户文件夹

python - 如何使用 Python (Ubuntu) 创建桌面快捷方式?

windows - 允许用户在 Inno Setup 中为图标/快捷方式选择热键

powershell - 如何使用 Pester 模拟 $host.ui.PromptForChoice

android - 如何定义网站屏幕快捷图标?

windows - windows环境变量名可以带点吗?