New AD group creation

Jacob Durham
Jacob Durham used Ask the Experts™
on
I am wanting to create security group for filtering purposes.

They do not exist yet and I am wanting to create them.

I would like to get all my AD user and select the value of the "Division" field.

With that field I'd like to add them to a group in an OU called "SafetyNet"

If the group that matches the name of their division exist - they would be added to that group. If not, the group would be created and then they would be added.

I imagine it would look something like this:



$users = get-aduser -properties * -filter {enabled -eq '$true' -and division -ne '$null'}

foreach ($user in $users)

{add-adgroupmember -Identity {

    Get-ADGroup $user.division 
    (if (unsure what goes here))

{}

else {
    new-adgroup -name $user.division -SamAccountName $user.division -GroupCategory Security -GroupScope global -path OU=safetynet,DC=smh,DC=org
}


}}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Co-Founder and Chief Architect
Top Expert 2016
Commented:
Something like this, with a few notes.

-I dunno how many domain controllers you have, but you may need to wait after new groups are created for it to propagate.  I added 10.
-If user is already in the group, suppress the action, in case you want to run it multiple times.

$rootOU = "OU=safetynet,DC=smh,DC=org"
$users = Get-ADUser -Filter {enabled -eq $true} -Properties * | ?{ $_.Division -ne $null }

foreach ($user in $users)
{
    $cn = $user.Division
    try 
    {
        Get-ADGroup -Identity $cn
    }
    catch
    {

        Write-Host "Creating new group $cn at $rootOU" -ForegroundColor Cyan
        New-ADGroup -Name $cn -SamAccountName $cn -GroupCategory Security -GroupScope Global -Path $rootOU
        $wait = 0
        while($wait -lt 10)
        {
            Write-Host "Waiting $(10-$wait) seconds for AD propagation" -ForegroundColor Yellow
            Start-Sleep -Seconds 1
            $wait++
        }

    }

    if (!(Get-ADPrincipalGroupMembership -Identity $user | select -ExpandProperty name).Contains($cn))
    {
        Write-Host "Adding $($user.SAMAccountName) to $cn" -ForegroundColor Green
        Add-ADGroupMember -Identity $cn -Members $user
    }

}

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial