Question:
In the last week, I have come across PowerShell and ActiveDirectory for the first time. I would like to be able to find a list of users that aren’t Admins or Domain Admins.
So far, I know how to get all the properties for all ActiveDirectory users with the following command/statement:
1 2 |
Get-ADUser -Filter * -Properties * |
What I would like to do is to print out just the usernames of current ActiveDirectory users – that are not Admins or Domain Admins.
Here is some pseudocode/Powershell code of what I am trying to do:
1 2 3 4 5 6 7 |
$users = Get-ADUser -Filter * -Properties * foreach($u in $users){ if ($u isn't an administrator OR $u isn't a domain administrator){ Write-Host "User Name:" $u.Name } } |
When I run the Get-ADUser -Filter * -Properties *
command, I am seeing the MemberOf
property for each user – which I’m thinking may be a clue. I have also heard of AdminCount
from various sources found via Google (is there something called DomainAdminCount
?).
I have been asked specifically to not use the PowerShell extension for ActiveDirectory – even though various sources say having this extension will make it easier.
I have spent about 2 hours testing various combinations of statements, but my novice PowerShell status isn’t helping me too much. I would be grateful for any assistance, and some clear explanations behind any feedback.
Answer:
That’s pretty easy task and you do not need to retrieve all users first and loop:
1 2 3 4 5 |
$DomainsAdminsDn = (Get-ADGroup 'Domain Admins').DistinguishedName Get-ADUser -Filter { -not (memberof -eq $DomainsAdminsDn) } # OR Get-ADUser -LDAPFilter "(!(memberof=$DomainsAdminsDn))" |
You can do the same with any other group.
EDIT:
Reversed queries, to return account that are not in group(s). BTW, this won’t work:
1 2 |
Get-ADUser -Filter { memberof -ne $DomainsAdminsDn } |
It will skip over all accounts that are not members of any other group than default one.