> 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

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

<figure><img src="/files/U3BSAsKpTYpdhHdlrewH" 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>" %}
