Within the InitializeSetup() function among other actions, when the installer is ran, I would like the installer to retrieve the current UPN. The UserName variable is not sufficient enough. I have also tried methods discussed here utilizing the WTSQuerySessionInformation() function but they don't seem to return what I am looking for. Depending on the organization and setting the UPN should often return some sort of an email address which I am looking for. Can someone shed some light on how to return the full UPN value as a string? Thank you.
EDIT:
I have also tried the GetUserNameExW() function passing in value 8 as an input which refers to UserNamePrincipal, however I am returning an empty value it seems.
function GetUserNameExW(NameFormat: Integer; lpNameBuffer: string; var nSize: DWORD): Boolean;
external '[email protected] stdcall';
var
NumChars: DWORD;
OutStr: string;
name: string;
begin
SetLength(OutStr, NumChars);
GetUserNameExW(8, OutStr, NumChars);
name := Copy(OutStr,1,NumChars);
CodePudding user response:
The correct code to call GetUserNameExW
to get the current user's userPrincipalName
(UPN) attribute would look like this:
function GetUserNameExW(NameFormat: Integer; lpNameBuffer: string; var nSize: DWORD): Boolean;
external '[email protected] stdcall';
function GetUserPrincipalName(): string;
var
NumChars: DWORD;
OutStr: string;
begin
result := '';
NumChars := 0;
if (not GetUserNameExW(8, '', NumChars)) and (DLLGetLastError() = 234) then
begin
SetLength(OutStr, NumChars);
if GetUserNameExW(8, OutStr, NumChars) then
result := Copy(OutStr, 1, NumChars);
end;
end;
The value 8
for the NameFormat
parameter corresponds to NameUserPrincipal
in the EXTENDED_NAME_FORMAT
enumeration, and the value 234
is API value ERROR_MORE_DATA
.
However--as I pointed out in a comment--if you are looking for an email address, this would not be the code to do that because userPrincipalName
(UPN) is a separate user attribute (in fact, in many, if not most organizations, the UPN is different from the user's email address). Also, if you are assuming the UPN to be the same as one of the user's email email addresses, this would also be an incorrect assumption, as the UPN's value is very often not in the list of valid email addresses for a user.
The point is that if you are looking for a reliable way to get a valid email address for a user, the UPN is not going give you one.
CodePudding user response:
I have managed to the solve this issue myself but still not 100% sure on why my previous iteration resulted in odd behavior.
Essentially, I had to add an if check before:
if GetUserNameExW(8, OutStr, NumChars) then