Is there a way to get the path of an .ico of a short cut? I know how to change the shortcuts icon, but how do I find the path of the shortcut's icon file?
CodePudding user response:
You could use below function.
It handles both 'regular' shrotcut files (.lnk) as well as Internet shortcut files (.url)
function Get-ShortcutIcon {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Alias('FullName')]
[string]$Path # needs to be an absulute path
)
switch ([System.IO.Path]::GetExtension($Path)) {
'.lnk' {
$WshShell = New-Object -ComObject WScript.Shell
$shortcut = $WshShell.CreateShortcut($Path)
$iconPath = $shortcut.IconLocation
$iconInfo = if ($iconPath -match '^,(\d )') {
[PsCustomObject]@{ IconPath = $shortcut.TargetPath; IconIndex = [int]$matches[1] }
}
else {
[PsCustomObject]@{ IconPath = $iconPath; IconIndex = 0 }
}
# clean up
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($shortcut)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($WshShell)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
# return the icon information
$iconInfo
}
'.url' {
$content = Get-Content -Path $Path -Raw
$iconPath = [regex]::Match($content, '(?im)^\s*IconFile\s*=\s*(.*)').Groups[1].Value
$iconIndex = [regex]::Match($content, '(?im)^\s*IconIndex\s*=\s*(\d )').Groups[1].Value
[PsCustomObject]@{ IconPath = $iconPath; IconIndex = [int]$iconIndex }
}
default { Write-Warning "'$Path' does not point to a '.lnk' or '.url' shortcut file.." }
}
}