DelegateType Reflection
getDelegationType
function getDelegateType {
Param (
[Parameter(Position = 0, Mandatory = $True)] [Type[]] $func,
[Parameter(Position = 1)] [Type] $delType = [Void]
)
$type = [AppDomain]::CurrentDomain.
DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('ReflectedDelegate')),
[System.Reflection.Emit.AssemblyBuilderAccess]::Run).
DefineDynamicModule('InMemoryModule', $false).
DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass',
[System.MulticastDelegate])
$type.
DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $func).
SetImplementationFlags('Runtime, Managed')
$type.
DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $delType, $func).
SetImplementationFlags('Runtime, Managed')
return $type.CreateType()
}Notes and other stuff
Creating new delegate type for GetUserName method in Advapi32.dll
Getting to understand the parameters in PowerShell. First using Add-Type to create a delegate type for me.
Add-Type creates the delegation type when the assembly is compiled, but we will need to create this manually.
Now we can view our current loaded assemblies.

View parameter types for GetUserName method.

Using getDelegateType function to create new delegate type for GetUserName
Other examples
LoadLibrary
Getting to understand the delegate type:

Confirming our delegate type:

Final code to call LoadLibrary
Last updated