If you’ve got an active directory group with a lot of members, this command can be helpful. It returns all users in the group you specify. Easily piped into a text file for quick reporting.
dsquery group -name "adGroup"|dsget group -members|dsget user -samid -email -display
Pretty simple and straight forward. Just another useful dsquery command. This one returns all computers in the domain.
dsquery * domainroot -filter "&(ObjectCategory=computer)" -attr distinguishedName -limit 0
Here is a quick way to retrieve the last logon date and time of a user. This queries AD for a specific username and returns distinquishedName, lastLogon and lastLogonTimestamp. In a domain with only 1 DC, lastlogon will be what you use. However, in a multiple DC domain all domain controllers will have different lastLogon timestamps. So you’ll need to query on lastLogonTimestamp which should comeback with the latest date and time replicated between the DC’s.
Then use w32time to convert the lastLogon or lastLogonTimestamp to a human readable format.
#return name and LastLogon of user. Change username for who you’re looking for
dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(sAMAccountName=username))" -attr distinguishedName lastLogon lastLogonTimestamp -limit 0
#convert lastlogon to date and time
w32tm.exe /ntte 129552322651555903
From time to time I like to run this command to see what computers have been inactive for x weeks. In this case, it’s all computer inactive for 10 weeks
dsquery computer -inactive 10
Once I verify I want to delete them all, I run the below statement. The statement uses Directory Services Restore Mode (DSRM) to delete all computers who have not checked into AD in 10 weeks. It has unicode options (-uco) and no prompt (don’t ask me if I want to delete it).
dsquery computer -inactive 10 -uco |dsrm -uci -noprompt
Occasionally I’ll get an error about leaf objects. Simply add the -subtree switch and you’ll delete them successfully.
dsquery computer -inactive 10 -uco |dsrm -uci -noprompt -subtree
In a larger AD environments it’s hard to find which OU a user or computer may be in. If you want to apply policy to that OU only, or maybe there is a template user in that OU, I use these commands to speed up the process of locating them.
#determine what OU a computer is in. Change computername to what you’re looking for.
dsquery * forestroot -filter "(&(ObjectCategory=Computer)(sAMAccountName="computername*"))" -attr distinguishedName -limit 0
#determine what OU a user is in. Change username to what you’re looking for.
dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(sAMAccountName=username*))" -attr distinguishedName -limit 0
