Active Directory: Querying User Accounts

Active Directory: Querying User Accounts


Various scripting and command-line methods for querying Active Directory for a list of users.



Directory Services


DSQuery User


Query a list of all users

    dsquery user -limit 0

Query disabled users

    dsquery user -limit 0 -disabled

DSGet User


Query disabled users and list their sAMAccountNames.

    dsquery user -limit 0 -disabled | dsget user -samid

DSQuery *


Query for all users and retrieve sAMAccountName and cn.

    dsquery * -filter "(&(objectCategory=person)(objectClass=user))" -limit 0 -attr sAMAccountName cn

VBScript


Query for all users and display the "pre-Windows 2000 logon" name and distinguished name of each:

Option Explicit

Dim adoCommand, adoConnection, strBase, strFilter, strAttributes
Dim objRootDSE, strDNSDomain, strQuery, adoRecordset, strName, strDN

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")
strBase = "<LDAP://" & strDNSDomain & ">"

' Filter on user objects.
strFilter = "(&(objectCategory=person)(objectClass=user))"

' Comma delimited list of attribute values to retrieve.
strAttributes = "distinguishedName,sAMAccountName"

' Construct the LDAP syntax query.
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 200
adoCommand.Properties("Timeout") = 30
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF
    ' Retrieve values and display.
    strDN = adoRecordset.fields("distinguishedName").Value
    strName = adoRecordset.Fields("sAMAccountName").Value
    Wscript.Echo "Logon Name: " & strName & ", DN: " & strDN
    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

' Clean up.
adoRecordset.Close
adoConnection.Close


PowerShell


ADSI


    $adsiSearcher = [adsisearcher]'(&(objectCategory=person)(objectClass=User))'
$adsiSearcher.searchroot = 'LDAP://DC=Contoso,DC=Internal'
$searcherResults = $adsiSearcher.findall()

Active Directory module


Import the Windows ActiveDirectory module and retrieve a list of all users

    Import-Module ActiveDirectory
    Get-ADUser -filter *

Quest ActiveRoles snapin


Import the Quest PowerShell module and retrieve a list of all users

    Add-PSsnapin Quest.activeroles.admanagement
    Get-QADUser -SizeLimit 0
Sort by: Published Date | Most Recent | Most Useful
Comments
Page 1 of 1 (1 items)