Home > Software design >  Check to See if User is part of any of certain AD groups
Check to See if User is part of any of certain AD groups

Time:04-19

I'm fairly new to powershell. I'm hoping to get direction on how I can task to work.

So part of my new hire script is to ensure a user account that gets created is surely added to Office ALL group. If it doesn't get added for some reason, I need a way to identity which account didn't get added.

We have office group office name that starts with Province/state Like ON,BC,AB and end with [email protected]

$ADgroupofAlloffices= $provincearray | ForEach-Object -process {Get-ADGroup -Filter "mail -like '$_-*'" -Properties Mail |
Where-Object {$_.Mail -LIKE "*[email protected]"} |
 Select-Object DistinguishedName | Sort-Object -Property Samaccountname}

This is my query to get all the groups by DistinguishedName. I have than more 30 groups.

Now I need away to check to see if the new hire account is part of this group as part of the final portion of over all script.

$user_groups = (Get-ADUser -Identity $ADUseraccount -Properties memberof | Select-Object memberof).memberof

I know with this I can get all the group of users.

How I check if AD user is part any of these office groups and let me know if user is not part any of these groups.

Let me know where need to do more search on finding solution for this. Scratching my head here.

CodePudding user response:

Several ways to do this, here is one, first the way you're getting the Office Groups can be optimized using AD Filtering only, with some string manipulation. You can iterate over the $provArray to generate an array of strings which then gets joined and combined into a single LDAP Filter, in example with the Provinces / States provided in your question the filter would be something like this:

(|(mail=ON*[email protected])(mail=BC*[email protected])(mail=AB*[email protected]))

Then after you query for all the groups, you can get an array with the DistinguishedName of all these groups ($officeGroups) which we can use to compare with the memberOf attribute of the user:

$provArray = 'ON', 'BC', 'AB' # and more here
$filter = foreach($i in $provArray) {
    "(mail=$i*[email protected])"
}
$filter = "(|$(-join $filter))"
$officeGroups = (Get-ADGroup -LDAPFilter $filter).DistinguishedName

$user = (Get-ADUser 'someuser' -Properties memberof).memberof
if($user.where{ $officeGroups -contains $_ }) {
    'user is a member of at least one office group'
    # do something here
}
else {
    'user is not a member of any office groups'
    # do something here
}

CodePudding user response:

Since you already have the distinguished name of all of the groups you're interested, you can just test if any of the groups that the user is a member of is in that list and go from there.

$OfficeGroup = $ADgroupofAlloffices | Where{$_.DistinguishedName -in $user_groups}
If(!$OfficeGroup){Write-Warning "User is not in an office group"}
  • Related