Powershell: Add all domain users to a group, but exclude users in multiple OU’s

#Import the Module, and silently continue if its already loaded.
Import-Module "ActiveDirectory" -Force -ErrorAction SilentlyContinue

#This is the new group we are creating, we will add the users to this group.
New-ADGroup -Name CorpUsers -GroupCategory Security -GroupScope Universal -Path "ou=Vendors,dc=dot45,dc=mine,dc=nu" -DisplayName "Corp Users" -Description "Members of this group are able to authenticate to the network using Cisco ISE"

#Here we are pulling all domain users, then filtering it with the where-object cmdlet, then filling the array.
$CorpUsers = Get-ADuser -Filter * -SearchBase "DC=dot45,DC=mine,DC=nu" | Where-Object {$_.DistinguishedName -notlike "*OU=Termed,DC=dot45,DC=mine,DC=nu" -and $_.DistinguishedName -notlike "*OU=Vendors,DC=dot45,DC=mine,DC=nu"}# | foreach-object
#Grabbing the sam accountname, since its easier to read in a log. you can skip this if you want the distinguished name in your log file.
{$_.samaccountname}

#This loop adds each user we found above to the group we just created, and logs the username to the text file.
foreach ($user in $CorpUsers)
{
write-host $user | out-file C:\CorpUsers.txt -append
Add-ADGroupMember -Identity CorpUsers -Member $user
}

About the Author

Leave a Reply

You may also like these