Thursday 30 March 2017

How To Automatically Add OU Users To Security Groups


Import-Module ActiveDirectory
Get-ADGroupMember –Identity $ShadowGroup | Where-Object {$_.distinguishedName –NotMatch $OU} | ForEach-Object {Remove-ADPrincipalGroupMembership –Identity $_ –MemberOf $ShadowGroup –Confirm:$false}
Get-ADUser –SearchBase $OU –SearchScope OneLevel –LDAPFilter "(!memberOf=$ShadowGroup)" | ForEach-Object {Add-ADPrincipalGroupMembership –Identity $_ –MemberOf $ShadowGroup}

(caution if you have users that are not a part of this OU, they will be removed from the group specified in $shadowgroup, if you don't want this remove the line in red)

To automate the script:
Below is an example Action on a scheduled task to run a PowerShell script on a Windows 2008 Server.
Action: Start a program
Program/script: C:\Windows\system32\windowspowershell\v1.0\powershell.exe
Add arguments (optional): -command C:\scripts\shadow-group.ps1

 I'm sure the above can be repeated using servers above 2008. 

*You will need a supervisor/ad account with admin privileges to run this.

Credit: Where I first found the info


No comments:

Post a Comment