Last active
August 1, 2020 16:38
-
-
Save nylyst/5f109777892483aa9a334f86ce930854 to your computer and use it in GitHub Desktop.
Powershell to register a dll without regsvr32.exe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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
PS H:> C:\Users\w\Downloads\RegisterDLL.ps1
Get-Process : Cannot find a process with the name "powershell". Verify the process name and call the cmdlet
again.
At C:\Users\w\Downloads\RegisterDLL.ps1:40 char:73
Cannot convert argument "hWnd", with value: "", for "CallWindowProc" to type "System.IntPtr": "Cannot
convert null to type "System.IntPtr"."
At C:\Users\w\Downloads\RegisterDLL.ps1:40 char:73