| Platform SDK: Active Directory, ADSI, and Directory Services |
The following code fragments read the canonicalName property of the Administrator.
//Read the canonicalName of Administrator
#include <wchar.h>
#include <objbase.h>
#include <activeds.h>
void wmain( int argc, wchar_t *argv[ ])
{
//Intialize COM
CoInitialize(NULL);
HRESULT hr = S_OK;
//Get rootDSE and the domain container's DN.
IADs *pObject = NULL;
LPOLESTR szPath = new OLECHAR[MAX_PATH];
VARIANT var;
hr = ADsOpenObject(L"LDAP://rootDSE",
NULL,
NULL,
ADS_SECURE_AUTHENTICATION, //Use Secure Authentication
IID_IADs,
(void**)&pObject);
if (FAILED(hr))
{
wprintf(L"Not Found. Could not bind to the domain.\n");
if (pObject)
pObject->Release();
return;
}
hr = pObject->Get(L"defaultNamingContext",&var);
if (SUCCEEDED(hr))
{
wcscpy(szPath,L"LDAP://");
wcscat(szPath,L"cn=Administrator,cn=Users,");
wcscat(szPath,var.bstrVal);
VariantClear(&var);
if (pObject)
{
pObject->Release();
pObject = NULL;
}
//Bind to the Administrator user object.
hr = ADsOpenObject(szPath,
NULL,
NULL,
ADS_SECURE_AUTHENTICATION, //Use Secure Authentication
IID_IADs,
(void**)&pObject);
if (SUCCEEDED(hr))
{
//
LPOLESTR pwszArray[] = {L"canonicalName"};
DWORD dwArrayItems = sizeof(pwszArray)/sizeof(LPOLESTR);
VARIANT vArray;
VariantInit(&vArray);
// Build a Variant of array type, using the specified string array.
hr = ADsBuildVarArrayStr(pwszArray, dwArrayItems, &vArray);
if (SUCCEEDED(hr))
{
hr = pObject->GetInfoEx(vArray,0L);
hr = pObject->Get(L"canonicalName", &var);
if (SUCCEEDED(hr))
wprintf(L"canonicalName: %s\n",var.bstrVal);
else
wprintf(L"Get failed with hr: %x\n",hr);
VariantClear(&var);
}
}
if (pObject)
pObject->Release();
}
//Uninitialize COM
CoUninitialize();
return;
}
'Read the canonicalName of Administrator
Dim rootDSE As IADs
Dim user As IADs
sPrefix = "LDAP://"
Set rootDSE = GetObject(sPrefix & "rootDSE")
If (Err.Number <> 0) Then
BailOnFailure Err.Number, "on GetObject method"
End If
sDomain = rootDSE.Get("defaultNamingContext")
If (Err.Number <> 0) Then
BailOnFailure Err.Number, "on Get method"
End If
sUserDN = "cn=Administrator,cn=users," + sDomain
'''''''''''''''''''''''''''''''''''''''
'Bind to the Administrator user
'''''''''''''''''''''''''''''''''''''''
Set user = GetObject(sPrefix & sUserDN)
user.GetInfoEx Array("canonicalName"), 0
strText = "Canonical Name: " & user.Get("canonicalName")
If (Err.Number <> 0) Then
BailOnFailure Err.Number, "on Get method"
End If
show_items strText, sComputer
'''''''''''''''''''''''''''''''''''''''
'Display subroutines
'''''''''''''''''''''''''''''''''''''''
Sub show_items(strText, strName)
MsgBox strText, vbInformation, "Get canonicalName for Administrator"
End Sub
Sub BailOnFailure(ErrNum, ErrText) strText = "Error 0x" & Hex(ErrNum) & " " & ErrText
MsgBox strText, vbInformation, "ADSI Error"
WScript.Quit
End Sub