How to read AD displayname

随声附和 提交于 2019-12-08 08:14:32

问题


I am using Delphi pascal ver. 4 I have a user initials and need to get the active directory display name from the initials so I do not want to change AD just read - a function will be nice like this:

fullname, user :string;
user:='DKTB'

(call function)

fullname:=getAdDispayName(user);

(after call then fullname = 'Torben Bagge')

I have used google to find it but was only able to find it in C and not pascal.


回答1:


You can easily do this using the IDirectorySearch Interface. I made an quick example for you (don't forget to add proper error handling):

uses
  ActiveX,
  JwaAdsTlb, JwaActiveDS; // From Jedi ApiLib

function GetADDisplayName(const Username: String): String;
var
  hr: HRESULT;
  DirSearch: IDirectorySearch;
  SearchInfo: ADS_SEARCHPREF_INFO;
  hSearch: ADS_SEARCH_HANDLE;
  col: ADS_SEARCH_COLUMN;
  Filter: String;
  Attributes: array of PChar;
begin
  Result := 'Undefined Result';

  // Initialize COM
  CoInitialize(nil);

  try
    // Change line below with your domain name
    hr := ADsGetObject('LDAP://dc=contoso,dc=com',
      IID_IDirectorySearch, Pointer(DirSearch));
    Win32Check(Succeeded(hr));

    SearchInfo.dwSearchPref := ADS_SEARCHPREF_SEARCH_SCOPE;
    SearchInfo.vValue.dwType := ADSTYPE_INTEGER;
    SearchInfo.vValue.Integer := ADS_SCOPE_SUBTREE;

    hr := DirSearch.SetSearchPreference(@SearchInfo, 1);
    Win32Check(Succeeded(hr));

    Filter := Format('(&(objectClass=user)(sAMAccountName=%s))',
      [Username]);

    SetLength(Attributes, 1);
    Attributes[0] := 'displayName';

    // When using Dynamic Array with WinApi ALWAYS use pointer to first element!
    hr := DirSearch.ExecuteSearch(PChar(Filter), @Attributes[0],
      Length(Attributes), hSearch);
    Win32Check(Succeeded(hr));

    try
      hr := DirSearch.GetFirstRow(hSearch);
      Win32Check(Succeeded(hr));

      hr := DirSearch.GetColumn(hSearch, Attributes[0], col);
      if Succeeded(hr) then
      begin
        Result := col.pADsValues^.CaseIgnoreString;
        DirSearch.FreeColumn(@col);
      end;
    finally
      DirSearch.CloseSearchHandle(hSearch);
    end;
  finally
    // UnInitialize COM
    CoUninitialize;
  end;
end;


来源:https://stackoverflow.com/questions/13031002/how-to-read-ad-displayname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!