Skip to content

Instantly share code, notes, and snippets.

@bill-long
Created February 7, 2023 05:17
Show Gist options
  • Save bill-long/c4bb07113f2cae062bad80642aa602eb to your computer and use it in GitHub Desktop.
Save bill-long/c4bb07113f2cae062bad80642aa602eb to your computer and use it in GitHub Desktop.
param(
[Parameter()]
[ValidateSet("NameUnknown", "NameFullyQualifiedDN", "NameSamCompatible", "NameDisplay", "NameUniqueId", "NameCanonical", "NameUserPrincipal", "NameCanonicalEx", "NameServicePrincipal", "NameDnsDomain")]
[string]
$ExtendedNameFormat = "NameSamCompatible")
$extendedNameFormats = @{
"NameUnknown" = 0
"NameFullyQualifiedDN" = 1
"NameSamCompatible" = 2
"NameDisplay" = 3
"NameUniqueId" = 6
"NameCanonical" = 7
"NameUserPrincipal" = 8
"NameCanonicalEx" = 9
"NameServicePrincipal" = 10
"NameDnsDomain" = 12
}
$getUserNameExSig = @'
[DllImport("secur32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern byte GetUserNameEx (int nameFormat,
System.Text.StringBuilder userName, ref int userNameSize);
'@
$getLastErrorSig = @'
[DllImport("Kernel32.dll")]
public static extern uint GetLastError();
'@
Add-Type -MemberDefinition $getUserNameExSig -Name Api1 -Namespace Sspi
Add-Type -MemberDefinition $getLastErrorSig -Name Api2 -Namespace Win32
$sb = New-Object System.Text.StringBuilder(1024)
$size = 1024
$result = [Sspi.Api1]::GetUserNameEx($extendedNameFormats[$ExtendedNameFormat], $sb, [ref]$size)
if ($result -eq 0) {
$e = [Win32.Api2]::GetLastError()
Write-Host "GetUserNameEx failed with error code $e"
} else {
$sb.ToString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment