Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell and ActiveDirectory module - Find Users that are not members of particular groups

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:

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:

$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.

like image 950
Rob Avatar asked Mar 12 '13 04:03

Rob


2 Answers

That's pretty easy task and you do not need to retrieve all users first and loop:

$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:

Get-ADUser -Filter { memberof -ne $DomainsAdminsDn }

It will skip over all accounts that are not members of any other group than default one.

like image 179
BartekB Avatar answered Oct 03 '22 05:10

BartekB


I used a little bit of what you everyone contributed, and tweaked it. I needed to find out who wasn't apart of a group, and I only needed their name. Let me know if this helped you out.

$Internet_Users = Get-ADGroup -Filter {Name -like "Internet_Users" }
Get-ADUser -Filter { -not (memberof -eq $Internet_Users) -and (enabled -eq "True" -and objectclass -eq "user")} |Select Name | Export-CSV "C:\Users\YOURNAME\Documents\Enabled_Users_Without_Internet_Users_Group.csv"  
like image 31
Day Avatar answered Oct 03 '22 04:10

Day