如何用PowerShell统计EXE/DLL文件的嵌入图标数量
修正PowerShell脚本统计EXE/DLL图标数量
你的脚本运行报错的核心原因是ExtractIconExW的P/Invoke声明不符合需求:当需要传递NULL指针给输出参数以触发图标计数功能时,不能使用out IntPtr(该类型要求必须传递一个可写的变量引用),正确的做法是将这两个输出参数声明为指针类型IntPtr*,这样才能直接传递空指针。
以下是修正后的完整脚本:
function Get-IconCount { Param ( [parameter(Mandatory = $true)] [string] $SourceFile ) $code = @' using System; using System.Runtime.InteropServices; public class FileIconInfo { [DllImport("Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, SetLastError = true)] public static extern uint ExtractIconExW( string szFileName, int nIconIndex, IntPtr* phiconLarge, IntPtr* phiconSmall, uint nIcons ); } '@ try { Add-Type -TypeDefinition $code # 传递IntPtr.Zero作为空指针,nIconIndex设为-1触发计数 $iconCount = [FileIconInfo]::ExtractIconExW($SourceFile, -1, [IntPtr]::Zero, [IntPtr]::Zero, 0) } Catch { Write-Host -ForegroundColor Red "[ERROR] 调用ExtractIconExW失败: $_" return } Write-Host -ForegroundColor DarkYellow "文件中图标总数: $iconCount" return $iconCount }
关键修改说明
- 调整P/Invoke参数类型:将
phiconLarge和phiconSmall从out IntPtr改为IntPtr*,允许传递空指针IntPtr.Zero - 简化依赖:移除了不必要的
System.Drawing引用,因为计数功能不需要操作图标对象 - 修正调用参数:调用时传递
[IntPtr]::Zero替代$null,同时将nIcons设为0(该参数在计数场景下无意义)
运行示例
# 加载脚本 . .\Get-IconCount.ps1 # 统计shell32.dll的图标数量 Get-IconCount -SourceFile 'C:\Windows\System32\shell32.dll' # 统计mun文件的图标数量 Get-IconCount -SourceFile 'C:\Windows\SystemResources\imageres.dll.mun'
内容的提问来源于stack exchange,提问作者not2qubit
相关产品推荐
相关产品推荐

