Wednesday, October 4, 2017

Dynamically populate AD security groups using PowerShell

Run these PowerShell command as a daily task to refresh AD security groups to make them dynamically populated

Import-Module ActiveDirectory


#The command below will remove all of the members from the group named [group].
Get-ADGroupMember [group] | %{remove-adgroupmember [group] $_.Samaccountname -confirm:$false}
#The command below will get all enabled users that are a member of the [group]. Also it will only return users who have "users" in their distinguished name. Finally it will take all of the results and add them to the group [group].
Get-ADUser -Filter {(Enabled -eq "True")  -and (company -like "[company]")} | ? {($_.distinguishedname -like "*users*")} | %{add-adgroupmember [group] $_.samaccountname}

Example:

#The command below will remove all of the members from the group named sg-SCCM.Contoso.Users.
Get-ADGroupMember sg-SCCM.Contoso.Users | %{remove-adgroupmember sg-SCCM.Contoso.Users $_.Samaccountname -confirm:$false}
#The command below will get all enabled users that are a member of the Contoso company. Also it will only return users who have "users" in their distinguishded name. Finally it will take all of the results and add them to the group sg-SCCM.Contoso.Users.
Get-ADUser -Filter {(Enabled -eq "True")  -and (company -like "Contoso")} | ? {($_.distinguishedname -like "*users*")} | %{add-adgroupmember sg-SCCM.Contoso.Users $_.samaccountname}



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.