> For the complete documentation index, see [llms.txt](https://rfc1918.gitbook.io/offsec/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://rfc1918.gitbook.io/offsec/execution/powershell/c-assembly-in-powershell/add-type.md).

# Add-Type

Add-Type keyword lets us use the .NET framework to compile C# code containing Win32 API declarations and then call them.

{% hint style="danger" %}
Using Add-Type to compile C# assembly, the source code will temporarily be written to disk.&#x20;
{% endhint %}

<figure><img src="https://1029482190-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVonnsWh96xLbzU5ncJWZ%2Fuploads%2Fndxpw1yXVM9m0JDBRBdu%2Fimage.png?alt=media&amp;token=e46ec8c3-6864-4404-a292-2885846aaa7c" alt=""><figcaption></figcaption></figure>

## Example code:&#x20;

The [GetUserName](http://pinvoke.net/default.aspx/advapi32/GetUserName.html) function retrieves the name of the user associated with the current thread.

```powershell
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()
```

{% embed url="<https://www.pinvoke.net/default.aspx/advapi32.getusername>" %}
