Created
February 7, 2023 05:17
-
-
Save bill-long/c4bb07113f2cae062bad80642aa602eb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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