Thursday, 23 April 2020

Useful Active Directory Command-Line Operations


The commands below are a subset of the complete command list that perform queries, diagnostics or modifications to objects in an Active Directory. These commands can be useful for once-off or repeated tasks, and defining a source for bulk imports/modifications to objects.

Each command-line can be copied and pasted at the command prompt, if you use a batch file you'll need to reference variables with double-percent (%%).


Query a user from AD using WMI
wmic /node:"%DC%" /namespace:\\root\directory\LDAP path ds_user where "ds_cn='%username%'" GET ds_displayName,DS_UserPrincipalName,ds_cn,ds_name,ds_whenCreated

Show all replicated attributes in the AD Schema
dsquery * cn=schema,cn=configuration,DC=forestRootDomain -filter "(&(objectClass=attributeSchema)(objectCategory=attributeSchema)(!systemFlags:1.2.840.113556.1.4.803:=1))" -limit 0

Show an AD schema attribute
dsquery * cn=pwd-last-set,cn=schema,cn=configuration,DC=forestRootDomain

Given a list of user CNs, find them in the directory and report homeDirectory
for /f %i in (Users.txt) do @for /f "tokens=*" %m in ('"dsquery user -name %i"') do @for /f %p in ('"dsquery * %m -attr homeDirectory -l | find /i "\\" & if errorlevel 1 Echo NoHomeDirectory"') do @echo %i,%m,%p

Identify the DN of an Active Directory group
dsquery group -name %GroupName%

Find the current group scope of a security group
dsget group %GroupDN% -scope -secgrp

Change a group's scope to universal, a stepping stone for conversion
dsmod group %GroupDN% -scope u

Change a universal group's scope to global or local
dsmod group %GroupDN% -scope l | g

Modify the UPN for a user
dsmod user "%userdN%" -upn user@domain

After identifying one or more accounts without a UPN, set the UPN for each
for /f "skip=1 tokens=1,2-3" %i in (NoUPN.txt) do dsmod user "%j %k" -upn %i@%upnsuffix%

Find all user accounts with a UPN, and count the DNs returned
dsquery * domainroot -filter "&(objectclass=user)(objectcategory=person)(userprincipalname=*)" -s %server% | find /i /c "user"

Find all user accounts without a UPN, and count the DNs returned
dsquery * domainroot -filter "&(objectclass=user)(objectcategory=person)(!(userprincipalname=*))" -s %server% | find /i /c "user"

Identify user accounts without a UPN to be corrected
dsquery * %OU% -filter "&(objectclass=user)(objectcategory=person)(!(userprincipalname=*))" -s %server% -scope onelevel -attr name distinguishedname > NoUPN.txt

Determine whether an attribute is replicated in AD through bitwise AND
dsquery * cn=%AttributeName%,cn=schema,cn=configuration,dc=forestRootDomain -filter "!(&(systemFlags:1.2.840.113556.1.4.803:=1))"

Find customised Service Connection Points of type RISServerdsquery * -filter "&((objectClass=ConnectionPoint)(objectCategory=ServiceConnectionPoint)(keywords=RISServer))" -attr serviceDNSName

Find intellimirror SCPs fpr RIS servers
dsquery * -filter "&((objectClass=ConnectionPoint)(objectCategory=IntellimirrorSCP)(netbootServer=*))" -attr netbootServer

Query for the display specifiers in the AD user classdsquery * "CN=user-Display,CN=409,CN=DisplaySpecifiers,CN=Configuration,%forestrootDomain%" -attr *

Find computers and their description from the ADdsquery * -filter "(&(objectClass=Computer)(objectCategory=Computer))" "%rootDN%" -attr cn description

Use LDP to search for tombstoned objects in ADBase DN: CN=Deleted Objects,%domainRoot%, Filter: (isDeleted=*), Extended Search, Add control: 1.2.840.113556.1.4.417

Bulk modify of mailbox permissions
admodcmd -dn "%DN%" -f "(&(objectclass=user)(CN=%userFilter%*))" -addtomailboxrights %Domain%\%Group% ACE_MB_FULL_ACCESS

Check user attributes from AD (division, department, home drive, email)for /f "tokens=1-3" %i in (%users.txt%) do @for /f "tokens=*" %m in ('"@dsquery user -name %i"') do @for /f "tokens=1-10" %q in ('"@dsquery * %m -attr CN department division mail homeDirectory homedrive find /i /v "homeDirectory""') do @echo %q,%r,%s,%t,%u,%v,%w,%x,%y >> UserInformation.csv

Set a Service Principal Name for an alias against the host computer accountsetspn -A HOST/%alias%.domain.com %server%

Find the computer object advertising a specific SPN
dsquery * -filter "(&(objectClass=Computer)(objectCategory=Computer)(servicePrincipalName=*SPN*))" -attr cn servicePrincipalName distinguishedName

Export group objects from AD to a CSV fileadfind -b "domainRoot" -f "objectclass=group" cn samaccountname -csv

Servers in the directory and their descriptiondsquery * dc=common,dc=local -filter "(&(objectCategory=Computer)(objectClass=Computer)(operatingSystem=*server*))" -limit 0 -attr cn description

Forest/Domain Functional Levels
ldifde -d cn=partitions,cn=configuration,dc=%domain% -r "((systemFlags=3)(systemFlags=-2147483648))" -l msds-behavior-version,dnsroot,ntmixeddomain,NetBIOSName -p subtree -f con (see http://support.microsoft.com/kb/322692 and http://support.microsoft.com/kb/224386)

Forest/Domain Functional Levelsdsquery * cn=partitions,cn=configuration,dc=%domain% -filter "((systemFlags=3)(systemFlags=-2147483648))" -attr msDS-Behavior-Version Name dnsroot ntmixeddomain NetBIOSName (see http://support.microsoft.com/kb/322692 and http://support.microsoft.com/kb/224386)

Lookup SRV records from DNS
nslookup -type=srv _ldap._tcp.dc._msdcs.{domainRoot}

Find when the AD was installeddsquery * cn=configuration,DC=forestRootDomain -attr whencreated -scope base

Enumerate the trusts from the specified domaindsquery * "CN=System,DC=domainRoot" -filter "(objectClass=trustedDomain)" -attr trustPartner flatName

Modify ACLs using dsacls (account ACL, not mailbox rights)dsacls "%userDN%" /G "%Domain%\%Group%:CA;Send As"

Information on existing GPO’s
dsquery * "CN=Policies,CN=System,domainRoot" -filter "(objectCategory=groupPolicyContainer)" -attr displayName cn whenCreated gPCFileSysPath

FSMO Rolesntdsutil roles Connections "Connect to server %logonserver%" Quit "select Operation Target" "List roles for conn server" Quit Quit Quit

Domain ControllersNltest /dclist:%userdnsdomain%

Domain Controller IP Configurationfor /f %i in ('dsquery server -domain %userdnsdomain% -o rdn') do psexec \\%i ipconfig /all >> DC_IPConfig.txt

Stale computer accounts
dsquery computer domainroot -stalepwd 180 -limit 0 > ComputerAccounts+180.txt

Stale user accountsdsquery user domainroot -stalepwd 180 -limit 0 > UserAccounts+180.txt

Disabled user accountsdsquery user domainroot -disabled -limit 0 > UserAccountsDisabled.txt

AD Database disk usagefor /f %i in ('dsquery server -domain %userdnsdomain% -o rdn') do dir \\%i\d$\ntds >> NTDS_Size_%userdomain%.txt

Global Catalog Servers from DNSdnscmd %logonserver% /enumrecords %userdnsdomain% _tcp find /i "3268"

Global Catalog Servers from AD
dsquery * "CN=Configuration,DC=forestRootDomain" -filter "(&(objectCategory=nTDSDSA)(options:1.2.840.113556.1.4.803:=1))"

Users with no logon scriptdsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(!scriptPath=*))" -limit 0 -attr sAMAccountName sn givenName pwdLastSet distinguishedName

User accounts with no pwd requireddsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(userAccountControl:1.2.840.113556.1.4.803:=32))"

User accounts with no pwd expirydsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(userAccountControl:1.2.840.113556.1.4.803:=65536))"

User accounts that are disabled
dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(userAccountControl:1.2.840.113556.1.4.803:=2))"

User accounts with no password expiry and not disableddsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(userAccountControl:1.2.840.113556.1.4.803:=65536)(!userAccountControl:1.2.840.113556.1.4.803:=2))"

Tombstoned AD objects
Adrestore.exe (sysinternals utility)

Garbage Collection and tombstonedsquery * "cn=Directory Service,cn=Windows NT,cn=Services,cn=Configuration,DC=forestRootDomain" -attr garbageCollPeriod tombstoneLifetime

DSQuery authorised DHCP Servers
Dsquery * "cn=NetServices,cn=Services,cn=Configuration, DC=forestRootDomain" -attr dhcpServers

Group Policy Verification Toolgpotool.exe /checkacl /verbose

AD OU membership
dsquery computer -limit 0

AD OU membershipdsquery user -limit 0

List Service Principal Namesfor /f %i in ('dsquery server -domain %userdnsdomain% -o rdn') do setspn -L %i

Compare DC Replica Object Countdsastat –s:DC1;DC2;... –b:Domain –gcattrs:objectclass –p:999

Check AD ACLs
acldiag dc=domainTree

NTFRS Replica Setsfor /f %i in ('dsquery server -domain %userdnsdomain% -o rdn') do ntfrsutl sets %i

NTFRS DS View
for /f %i in ('dsquery server -domain %userdnsdomain% -o rdn') do ntfrsutl ds %i

Domain Controllers per siteDsquery * "CN=Sites,CN=Configuration,DC=forestRootDomain" -filter (objectCategory=Server)

DNS Zones in AD
for /f %i in ('dsquery server -o rdn') do Dsquery * -s %i domainroot -filter (objectCategory=dnsZone)

Subnet information
Dsquery subnet –limit 0

List Organisational Units
Dsquery OU

ACL on all OUsFor /f “delims=” %i in ('dsquery OU') do acldiag %i >> ACLDiag.txt

Domain Trusts
nltest /domain_trusts /v

AD Subnet and Site Informationdsquery * "CN=Subnets,CN=Sites,CN=Configuration,DC=forestRootDomain" -attr cn siteObject description location

AD Site Information
dsquery * "CN=Sites,CN=Configuration,DC=forestRootDomain" -attr cn description location -filter (objectClass=site)

Printer Queue Objects in ADdsquery * domainroot -filter "(objectCategory=printQueue)" -limit 0

Group Membership with user detailsdsget group "groupDN" -members dsget user -samid -fn -mi -ln -display -empid -desc -office -tel -email -title -dept -mgr

Site Links and Cost
dsquery * "CN=Sites,CN=Configuration,DC=forestRootDomain" -attr cn cost description replInterval siteList -filter (objectClass=siteLink)

Time gpresulttimethis gpresult /v > GPResult_%ComputerName%.txt 2<&1 Check time against Domain w32tm /monitor /computers:ForestRootPDC > %temp%\Time.txt

Domain Controller Diagnosticsdcdiag /s:%logonserver% /v /e /c

Domain Replication Bridgeheads
repadmin /bridgeheads

Replication Failures from KCCrepadmin /failcache

Inter-site Topology servers per siteRepadmin /istg * /verbose

Replication latency
repadmin /latency /verbose

Queued replication requestsrepadmin /queue *

Show connections for a DC
repadmin /showconn *

Replication summaryRepadmin /replsummary

Show replication partnersrepadmin /showrepl * /all

All DCs in the forest
repadmin /viewlist *

ISTG from AD attributesdsquery * "CN=NTDS Site Settings,CN=siteName,CN=Sites,CN=Configuration,DC=forestRootDomain" -attr interSiteTopologyGenerator

Return the object if KCC Intra/Inter site is disabled for each siteDsquery site dsquery * -attr * -filter "((Options:1.2.840.113556.1.4.803:=1)(Options:1.2.840.113556.1.4.803:=16))"

Find all connection objects
dsquery * forestRoot -filter (objectCategory=nTDSConnection) –attr distinguishedName fromServer whenCreated displayName

Find all connection schedulesadfind -b "cn=Configuration,DC=forestRootDomain" -f "objectcategory=ntdsConnection" cn Schedule -csv

Copy all Group Policy .pol files
for /f "tokens=1-8 delims=\" %i in ('dir /b /s \\%dc%\sysvol\%userdnsdomain%\policies\*.pol') do @echo copy \\%i\%j\%k\%l\%m\%n\%o %m_%n.pol

Extract the registry entries from each Group Policy pol filefor %i in (*.pol) do regview %i > %i.txt

Find policy changes for each policy
for /f "tokens=1,2 delims=," %i in (Output from 'Extract policy registry entries') do for /f "tokens=2 delims=:" %k in ('"find /i /c "valuename" %~nj*.txt find /i "%~nj""') do @echo %i,%j,%k

Domain Controller Netlogon entriesfor /f %i in ('dsquery server /o rdn') do echo %i & reg query \\%i\hklm\system\currentcontrolset\services\netlogon\parameters

Find site links that contain two sites with Domain Controllersfor /f "tokens=1,2 delims=-" %i in (Sites.txt) do @find /i "%i" DCs.txt >nul & if errorlevel 0 if not errorlevel 1 @find /i "%j" DCs.txt find /i /v "----------"

Find policy display name given the GUID
dsquery * "CN=Policies,CN=System,DC=domainRoot" -filter (objectCategory=groupPolicyContainer) -attr Name displayName

Find empty groupsdsquery * -filter "&(objectCategory=group)(!member=*)" -limit 0 -attr whenCreated whenChanged groupType sAMAccountName distinguishedName memberOf

Find a DC for each trusted domain
for /f "skip=1" %i in ('"dsquery * CN=System,DC=domainRoot -filter (objectClass=trustedDomain) -attr trustPartner"') do nltest /dsgetdc:%i

Verify automatic external LDAP referrals are workingdsquery * dc=other,dc=domain -s %localDC%

Check winlogon notification packages on DCs
for /f %i in ('dsquery server /o rdn') do @for /f "tokens=4" %m in ('"reg query \\%i\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa /v "Notification Packages" find /i "Notification""') do @echo %i,%m

Find out if a user account is currently enabled or disableddsquery user DC=%userdnsdomain:.=,DC=% -name %username% dsget user -disabled -dn

Find 2003 servers in the domain
dsquery * domainroot -filter "(&(objectCategory=Computer)(objectClass=Computer)(operatingSystem=*Server*))" -limit 0

Open DS query windowrundll32 dsquery,OpenQueryWindow

Check for a schema attributedsquery * "CN=Schema,CN=Configuration,DC=forestRoot" -filter "(&((cn=%ObjectName*)((objectCategory=classSchema)(objectCategory=attributeSchema))))"

Find servers and the description recorded with the computer accountdsquery * %domainRoot% -filter "(&(objectCategory=Computer)(objectClass=Computer)(operatingSystem=*Server*))" -limit 0 -attr cn distinguishedName Description

Find DCs in the specified site from AD
dsquery * "CN=%SiteName%,CN=Sites,CN=Configuration,DC=root,DC=local" -filter "&(objectClass=server)(objectCategory=server)"

Dump account lockout eventlog entries from all DCs for the last five daysfor /f %i in ('dsquery server -domain %userdnsdomain% -o rdn') do echo dumpel.exe -e 644 -l Security -m Security -s %i -c -d 5

Query for universal groups
dsquery * dc=%forestRootDomain% -filter "(&(objectCategory=group)(groupType=-2147483640))"

Find the link speed when connecting to the domainlinkspeed /s %domain%

Determine users that aren’t in a group
for /f "tokens=1-3" %i in (%users.txt%) do @for /f "tokens=*" %m in ('"@dsquery user -name %i"') do @echo %m & @dsget user %m -memberof -expand @findstr /i /c:"%m" /c:"%GROUP%" & echo.

Query group membershipdsquery group -name %GROUP% dsget group -members -expand > %GROUP%.members

Check whether users are in a group (from 'Query group membership')for /f "skip=1 tokens=1-3" %i in (%users.txt%) do @find /i "%i" %GROUP%.members >NUL & @if errorlevel 1 echo %i

Check whether users are in a group or not (from 'Query group membership')
for /f "tokens=1-3" %i in (%users.txt%) do @find /i "%i" %GROUP%.members >NUL & @if errorlevel 0 if not errorlevel 1 (echo %i Member) else (echo %i NotMember)

Return the DN of a list of usersfor /f %i in (%users.txt%) do @dsquery user -name %i

No comments:

Post a comment