Skip to content

Instantly share code, notes, and snippets.

@lihas
Forked from nylyst/RegisterDLL.ps1
Created July 28, 2017 19:23
Show Gist options
  • Save lihas/998edab6e9a4a15a4af4aff369ebbffb to your computer and use it in GitHub Desktop.
Save lihas/998edab6e9a4a15a4af4aff369ebbffb to your computer and use it in GitHub Desktop.
Powershell to register a dll without regsvr32.exe
$registerDLL = @"
namespace RegisterDLL {
using System;
using System.Runtime.InteropServices;
public static class Kernel32 {
[DllImport("kernel32", SetLastError=true, CharSet = CharSet.Ansi)]
public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);
[DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FreeLibrary(IntPtr hModule);
}
public static class User32 {
//[DllImport("user32.dll")]
//public static extern IntPtr CallWindowProc(WndProcDelegate lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr CallWindowProc(IntPtr wndProc, IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
}
}
"@
Add-Type -TypeDefinition $registerDLL
$dllPath = "C:\Full\Path\To.dll"
[System.IntPtr]$module = [RegisterDLL.Kernel32]::LoadLibrary($dllPath)
Write-Verbose "module = $module"
if(Test-Path -LiteralPath $dllPath)
{
Write-Verbose "Found $dllPath, attempting to register"
try
{
[System.IntPtr]$address = [RegisterDLL.Kernel32]::GetProcAddress($module, "DllRegisterServer")
write-Verbose "address = $address"
$finalResult = [RegisterDLL.User32]::CallWindowProc($address, $(Get-Process -Name powershell).Handle, 0, 0, 0)
write-Verbose "finalResult = $finalResult"
}
finally
{
[RegisterDLL.Kernel32]::FreeLibrary($module) | Out-Null
}
}
else
{
Write-Verbose "Failed to find $dllPath"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment