Add-Type
Add-Type keyword lets us use the .NET framework to compile C# code containing Win32 API declarations and then call them.
Using Add-Type to compile C# assembly, the source code will temporarily be written to disk.

Example code:
The GetUserName function retrieves the name of the user associated with the current thread.
powershell
$advapi32 = @'
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool GetUserName(System.Text.StringBuilder sb, ref Int32 length);
'@
Add-Type -MemberDefinition $advapi32 -Namespace Advapi32 -Name Util
$size = 64
$str = New-Object System.Text.StringBuilder -ArgumentList $size
[Advapi32.util]::GetUserName($str,[ref]$size) | Out-Null
$str.ToString()
Last updated