Jarrod
Jarrod

Reputation: 101

How can I loop through OU in AD to add users to various security groups?

I'm somewhat new to writing PS scripts, I usually only need simple one or two liners, but for this I'm trying to loop through a specific OU in Active Directory to find each users department, add "grp" before it and add them to the security group by that name. For example, a department might be something like 10005 so I'd like to add them to security group named "grp10005". Here's what I have but it isn't working.

Import-Module ActiveDirectory  

 $users = $i = $null  
 $strCC
 $strGRP = 'grp' & strCC

 $users = Get-ADUser -SearchBase "ou=Test,ou=OurUsers,ou=Logins,dc=domain,dc=com" -filter * {department -eq $strCC}  
 ForEach($user in $users)  
    {    
      Add-ADGroupMember 'strGRP' -Members $_.DistinguishedName
        -ErrorAction SilentlyContinue
      $i++  
    }  

Upvotes: 3

Views: 26520

Answers (2)

New Guy
New Guy

Reputation: 9166

I removed the syntax errors and modified the approach a bit.

Import-Module ActiveDirectory  

$users = $null  
$strDept = "Finance"
$strGRP = ('grp' + $strDept)

$users = Get-ADUser -SearchBase "ou=Test,ou=OurUsers,ou=Logins,dc=domain,dc=com" -Filter { Department -eq $strDept }  
ForEach($user in $users)  
{    
    Add-ADGroupMember 'strGRP' -Members $user.DistinguishedName
        -ErrorAction SilentlyContinue
}

Edit:

Based on the comments below it sounds like you are not wanting to use a filter at all but you want to check every user in the OU, find out what their current department is, then add them to a group by that name but with "grp" prefixed on to it.

Here is a possible solution:

Import-Module ActiveDirectory  

$users = $null  

$users = Get-ADUser -SearchBase "ou=Test,ou=OurUsers,ou=Logins,dc=domain,dc=com" -Filter * -Properties Department
ForEach($user in $users)  
{    
    Add-ADGroupMember ("grp" + $user.Department) -Members $user.DistinguishedName -ErrorAction SilentlyContinue
}

Upvotes: 5

Johan de Haan
Johan de Haan

Reputation: 1018

You can use the following code:

 Import-Module ActiveDirectory  

 $users = $null 
 $i = 0 
 $strCC = "CC"
 $strGRP = ("GroupName" + $strCC)

 $users = Get-ADUser -SearchBase "ou=Test,ou=OurUsers,ou=Logins,dc=domain,dc=com" -filter {department -eq $strCC}  
 ForEach($user in $users)  
    {    
      Add-ADGroupMember $strGRP -Members $user.DistinguishedName `
        -ErrorAction SilentlyContinue
      $i++  
    }  

Note the difference between the two types of loop:

$array | foreach-object {
Write-Host $_
}  

and:

foreach ($item in $array) {
Write-Host $item
}

Upvotes: 2

Related Questions