用于定位memberOf的C ++ LDAP Query

时间:2010-11-18 23:47:11

标签: c++ active-directory ldap

我目前正在尝试在c ++中执行LDAP查询以获取给定用户的memberOf属性。我有一个函数编写成功获取属性,如果它们只在一个组中。问题是,当他们在多个组中时,它只返回第一个组。当我在Active Directory浏览器中查看用户时,我可以看到它表示他们有2个memberOf条目,但是当我使用我的函数时,我只得到第一个。有没有办法修改我的功能以撤回所有条目,还是我完全走错了路?

bool FindADMembership(CStringArray* pUserArray,IDirectorySearch *pContainerToSearch, CString sAMAccountName){

if(pContainerToSearch==NULL||pUserArray==NULL)
    return false;

CString strSearchFilter;
strSearchFilter.Format("(&(objectClass=user)(objectCategory=person)(sAMAccountName=%s))", sAMAccountName);
BSTR b = strSearchFilter.AllocSysString();
LPOLESTR pszSearchFilter = b;
ADS_SEARCHPREF_INFO SearchPrefs;
SearchPrefs.dwSearchPref = ADS_SEARCHPREF_SEARCH_SCOPE;
SearchPrefs.vValue.dwType = ADSTYPE_INTEGER;
SearchPrefs.vValue.Integer = ADS_SCOPE_SUBTREE;
DWORD dwNumPrefs = 1;

LPOLESTR pszColumn = NULL;    
ADS_SEARCH_COLUMN col;
HRESULT hr;

IADs    *pObj = NULL;
IADs    * pIADs = NULL;

ADS_SEARCH_HANDLE hSearch = NULL; 
hr = pContainerToSearch->SetSearchPreference( &SearchPrefs, dwNumPrefs);
if (FAILED(hr))
    return false;


LPOLESTR pszNonVerboseList[] = {L"memberOf"};
LPOLESTR szName = new OLECHAR[MAX_PATH];
int iCount = 0;


hr = pContainerToSearch->ExecuteSearch(pszSearchFilter,    pszNonVerboseList,sizeof(pszNonVerboseList)/sizeof(LPOLESTR),&hSearch);
if ( SUCCEEDED(hr) )
{    
    hr = pContainerToSearch->GetFirstRow( hSearch);
    if (SUCCEEDED(hr))
    {
        while( hr != S_ADS_NOMORE_ROWS )
        {
            iCount++;
            while( pContainerToSearch->GetNextColumnName( hSearch, &pszColumn ) != S_ADS_NOMORE_COLUMNS )
            {
                hr = pContainerToSearch->GetColumn( hSearch, pszColumn, &col );
                if ( SUCCEEDED(hr) )
                {
                    if (0==wcscmp(L"memberOf", pszColumn))
                    {
                        wcscpy(szName,col.pADsValues->CaseIgnoreString);
                        pUserArray->Add(szName);
                    }

                    pContainerToSearch->FreeColumn( &col );
                }
                FreeADsMem( pszColumn );
            }  


            hr = pContainerToSearch->GetNextRow( hSearch);
        } 

    }
    else
        return false;

    pContainerToSearch->CloseSearchHandle(hSearch);
} 
else
    return false;

return true; }

编辑:

在此处理之后,这里是迭代结果的代码

if (0==wcscmp(L"memberOf", pszColumn)) {
    for(int i = 0; i < col.dwNumValues; i++)
    {
        wcscpy(szName, col.pADsValues[i].CaseIgnoreString);
        pUserArray->Add(szName);
    }
}

1 个答案:

答案 0 :(得分:1)

您需要检查值的数量并循环遍历它们以依次获取每个值 - pADSValues是一个可以包含&gt;的数组。 1个字符串。计数在dwNumValues中返回。

if (0==wcscmp(L"memberOf", pszColumn))
{
    // This code should actually be a loop for i = 0 to dwNumValues - 1
    // with each loop checking the next array entry in the list pADsValues
    wcscpy(szName,col.pADsValues->CaseIgnoreString);
    pUserArray->Add(szName);
}

请参阅文档here