Search notes:

PowerShell: Call ExtractStringFromDLL()

The following PowerShell snippet demonstrates how a string can be extracted from a DLL with the WinAPI function ExtractStringFromDLL.
The source code is mostly copied from this Stackoverflow answer.
add-type -typeDefinition @"
using System;
using System.Runtime.InteropServices;
using System.Text;

public class tq84_krnl {

  [DllImport("kernel32.dll",
      SetLastError = true,
      CharSet      = CharSet.Ansi
   )]
   private static extern IntPtr              LoadLibraryEx
   (
     [MarshalAs(UnmanagedType.LPStr)]string  lpFileName,
      IntPtr                                 hFile,
      uint                                   dwFlags
   );

  [DllImport("user32.dll"  ,
      SetLastError = true,
      CharSet      = CharSet.Auto
   )]
   private static extern int                 LoadString
   (
      IntPtr                                 hInstance,
      int                                    ID,
      StringBuilder                          lpBuffer,
      int                                    nBufferMax
   );

  [DllImport("kernel32.dll",
      SetLastError = true)]
  [return: MarshalAs(UnmanagedType.Bool)]
   private static extern bool                FreeLibrary
   (
      IntPtr                                 hModule
   );

  public static string ExtractStringFromDLL(string file, int number) {

      IntPtr lib = LoadLibraryEx(file, new IntPtr(0L), 32); // 32 = LOAD_LIBRARY_AS_IMAGE_RESOURCE
      StringBuilder result = new StringBuilder(2048);
      LoadString(lib, number, result, result.Capacity);
      FreeLibrary(lib);

      return result.ToString();
  }
}
"@
Github repository about-PowerShell, path: /examples/WinAPI/ExtractStringFromDLL.ps1

Using the function

The function can now be used to extract a few strings from different DLLs:
PS C:\> [tq84_krnl]::ExtractStringFromDLL("$env:SystemRoot\system32\Microsoft.Bluetooth.UserService.dll",   102)
PS C:\> [tq84_krnl]::ExtractStringFromDLL("$env:SystemRoot\system32\shell32.dll"                        , 21799)
PS C:\> [tq84_krnl]::ExtractStringFromDLL("$env:SystemRoot\system32\input.dll"                          ,  5035)

See also

Calling ExtractIconEx() with PowerShell

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/Windows/...', 1759612549, '216.73.216.149', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/Windows/PowerShell/examples/WinAPI/ExtractStringFromDLL(100): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78