Skip to content

Instantly share code, notes, and snippets.

@blacksun1
Created February 19, 2015 00:55
Show Gist options
  • Save blacksun1/9c23aa43ad49f640b49e to your computer and use it in GitHub Desktop.
Save blacksun1/9c23aa43ad49f640b49e to your computer and use it in GitHub Desktop.
function Get-UsersFullName {
$NAME_DISPLAY = [int] 3
$MethodDefinition = @'
[DllImport("secur32.dll", CharSet=CharSet.Auto, SetLastError=true)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern int GetUserNameEx (int nameFormat, StringBuilder userName, ref UInt32 userNameSize);
'@
$type = Add-Type -MemberDefinition $MethodDefinition `
-NameSpace Win32 -Name "Secur32" `
-Using "System.Text" -PassThru
$sb = New-Object -TypeName "System.Text.StringBuilder" -ArgumentList 1024
$rv = [int]([Win32.Secur32]::GetUserNameEx($NAME_DISPLAY, $sb, [ref][UInt32]($sb.Capacity)))
return $sb.ToString()
}
@blacksun1
Copy link
Author

This code doesn't work yet. I get the following...

Exception calling "GetUserNameEx" with "3" argument(s): "Cannot marshal 'return value': Invalid managed/unmanaged type combination
(Int32/UInt32 must be paired with I4, U4, or Error)."
At C:\Users\bruces\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:82 char:3
+   $rv = [int]([Win32.Secur32]::GetUserNameEx($NAME_DISPLAY, $sb, [ref][UInt32]($ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : MarshalDirectiveException

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment