I need to find out the name of the OU that the local computer (that is connected to the Active Directory) belongs to using WinAPI/C++. Any ideas?
Get OU (Organizational Unit) name that a local computer belongs to using C++
1.7k views Asked by ahmd0 AtThere are 3 answers
In theory, this is fairly simple: connect to the server with ADsOpenObject
, instantiate an IDirectorySearch
and invoke its ExecuteSearch
method, then use GetFirstRow
and GetNextRow
to walk through the result data (but for this query, you'll only expect one row).
In reality, however, all of this is COM -- so expect those half dozen (or so) function calls to be pretty much lost in at least a hundred lines of COM-cruftiness (and by the time the code is solid and robust, don't be surprised if it's closer to 1000 lines, most of which have no noticeable connection to Active Directory).
I should add that there are almost certainly other ways to do this -- as I recall, MS provides at least two or three different ways to access LDAP-type data. When I wrote some code for this, I initially tried to find which would be the cleanest, but gave up in frustration. There seemed to be no hope for cleanest -- at least at that time, I settled for "ugly but somewhat documented".
///////////////IDirectorySearch///////////////////////////////////////////////////////////
CComPtr<IDirectorySearch> pDSSearch;
hr = ADsGetObject( L"LDAP://DC=forest,DC=internal",
IID_IDirectorySearch,
(void**) &pDSSearch );
if ( !SUCCEEDED(hr) )
{
return 0;
}
LPWSTR pszAttr[] = { L"description", L"Name", L"distinguishedname" };
ADS_SEARCH_HANDLE hSearch;
DWORD dwCount = 0;
ADS_SEARCH_COLUMN col;
DWORD dwAttrNameSize = sizeof(pszAttr)/sizeof(LPWSTR);
// Search for all objects with the 'cn' property TESTCOMP.
hr = pDSSearch->ExecuteSearch(L"(&(objectClass=computer)(cn=TESTCOMP))",pszAttr ,dwAttrNameSize,&hSearch );
LPWSTR pszColumn;
while( pDSSearch->GetNextRow( hSearch) != S_ADS_NOMORE_ROWS )
{
// Get the property.
hr = pDSSearch->GetColumn( hSearch, L"distinguishedname", &col );
// If this object supports this attribute, display it.
if ( SUCCEEDED(hr) )
{
if (col.dwADsType == ADSTYPE_CASE_IGNORE_STRING)
wprintf(L"The description property:%s\r\n", col.pADsValues->CaseIgnoreString);
pDSSearch->FreeColumn( &col );
}
else
puts("description property NOT available");
puts("------------------------------------------------");
dwCount++;
}
pDSSearch->CloseSearchHandle(hSearch);
///////////////IDirectorySearch///////////////////////////////////////////////////////////
In this search you'll get
(*((col).pADsValues)).DNString "CN=TESTCOMP,OU=OUnit3,OU=OUnit,DC=forest,DC=internal"
So this is path to your TESTCOMP and I believe OUnit3 is what you want.
For a simple WINAPI (not COM) way to acces Active Directory in C or C++ see Lightweight Directory Access Protocol