Skip to content

Instantly share code, notes, and snippets.

@MyITGuy
Created June 26, 2025 13:45
Show Gist options
  • Save MyITGuy/86faa384275deddd4abc3a4cb37975ac to your computer and use it in GitHub Desktop.
Save MyITGuy/86faa384275deddd4abc3a4cb37975ac to your computer and use it in GitHub Desktop.
function Invoke-ExtractIcon {
[CmdletBinding(SupportsShouldProcess)]
Param(
[Parameter(Position = 0, Mandatory,HelpMessage = "Specify the path to the file.")]
[ValidateScript({Test-Path $_})]
[string]$Path,
[Parameter(HelpMessage = "Specify the folder to save the file.")]
[ValidateScript({Test-Path $_})]
[string]$Destination = ".",
[parameter(HelpMessage = "Specify an alternate base name for the new image file. Otherwise, the source name will be used.")]
[ValidateNotNullOrEmpty()]
[string]$Name,
[Parameter(HelpMessage = "What format do you want to use? The default is png.")]
[ValidateSet("ico","bmp","png","jpg","gif")]
[string]$Format = "png"
)
# inspired by https://community.spiceworks.com/topic/592770-extract-icon-from-exe-powershell
if ($PSVersionTable.PSVersion -lt [System.Version]'5.1') {
Write-Warning "PowerShell version $($PSVersionTable.PSVersion.ToString()) is not supported."
return
}
Write-Verbose "Starting $($MyInvocation.MyCommand)"
try {
Add-Type -AssemblyName System.Drawing -ErrorAction Stop
} catch {
Write-Warning "Failed to import System.Drawing"
Throw $_
}
switch ($format) {
"ico" {$ImageFormat = "icon"}
"bmp" {$ImageFormat = "Bmp"}
"png" {$ImageFormat = "Png"}
"jpg" {$ImageFormat = "Jpeg"}
"gif" {$ImageFormat = "Gif"}
}
$file = Get-Item $path
Write-Verbose "Processing $($file.fullname)"
#convert destination to file system path
$Destination = Convert-Path -Path $Destination
if ($Name) {
$base = $Name
} else {
$base = $file.BaseName
}
#construct the image file name
$out = Join-Path -Path $Destination -ChildPath "$base.$format"
Write-Verbose "Extracting $ImageFormat image to $out"
$ico = [System.Drawing.Icon]::ExtractAssociatedIcon($file.FullName)
if ($ico) {
#WhatIf (target, action)
if ($PSCmdlet.ShouldProcess($out, "Extract icon")) {
$ico.ToBitmap().Save($Out,$Imageformat)
Get-Item -path $out
}
} else {
#this should probably never get called
Write-Warning "No associated icon image found in $($file.fullname)"
}
Write-Verbose "Ending $($MyInvocation.MyCommand)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment