Calling user32.dll LoadImage from Powershell RRS feed

  • Question

  • Hi all,

    I'm trying to get the 256x256 icons from a resource file with powershell. It seems like LoadImage is the only way to get this since ExtractAssociatedIcon and LoadIcon only give you the 32x32 icon. So I tried to use it however the pointer i get as return is always 0.

    This is my current code

    $code = @"
    using System;
    using System.Drawing;
    using System.Runtime.InteropServices;
    using System.Text;
    namespace System {
    	public class ResourceExtractor {
    		public static string ExtractString(string file, int number) {
    			IntPtr lib = LoadLibrary(file);
    			StringBuilder result = new StringBuilder(2048);
    			LoadString(lib, number, result, result.Capacity);
    			return result.ToString();
    		public static Icon ExtractIcon() {
    			IntPtr lib = LoadLibrary("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");
    			IntPtr handle = LoadImage(lib, "#0", 1, 256, 256, 0x00000010);
    			return Icon.FromHandle(handle);
    		[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
    		public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);
    		[DllImport("user32.dll", CharSet = CharSet.Auto)]
    		public static extern int LoadString(IntPtr hInstance, int ID, StringBuilder lpBuffer, int nBufferMax);
    		[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] 
    		public static extern IntPtr LoadImage(IntPtr hinst, [MarshalAs(UnmanagedType.LPTStr)] string lpszName, uint uType, int cxDesired, int cyDesired, uint fuLoad);
    		[DllImport("kernel32.dll", SetLastError = true)]
    		[return: MarshalAs(UnmanagedType.Bool)]
    		public static extern bool FreeLibrary(IntPtr hModule);
    Add-Type -TypeDefinition $code -ReferencedAssemblies System.Drawing
    $icon = [System.ResourceExtractor]::ExtractIcon()

    I tried all kinds of variants with the lpzName. Imported the function with int, string, Marshalled string. Giving the function 0, "0", "#0", new IntPtr(0), "#32512"... all kinds of things that are supposed to work. I also tried loading shell32.dll to check if it's a problem with an exe file. But no luck.

    I'm kind of runing out of ideas and have no clue what i'm doing wrong here. If anyone has a hint or sees what's wrong i would highly appriciate it. Or alternatively another way to get the big icons from a resource file with powershell.

    Thanks & Regards

    Tuesday, June 19, 2018 11:12 PM

All replies