Skip to content

Instantly share code, notes, and snippets.

@briped
Created October 31, 2014 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briped/dc9e8c6f30caf703688e to your computer and use it in GitHub Desktop.
Save briped/dc9e8c6f30caf703688e to your computer and use it in GitHub Desktop.
Param(
[parameter(Mandatory=$true,
HelpMessage="Enter one or more AD groups to merge/copy from.")]
[string[]]
$SourceGroups,
[parameter(Mandatory=$true,
HelpMessage="Enter AD group to merge/copy to.")]
[string]
$TargetGroup,
[parameter(Mandatory=$false,
HelpMessage="Enter one or more AD groups with users to exclude from TargetGroup.")]
[string[]]
$ExcludeGroup
)
Import-Module -Name ActiveDirectory -ErrorAction SilentlyContinue
If (!(Get-ADGroup -Identity $TargetGroup | Out-Null))
{
Write-Warning -Message "The AD Group '$($TargetGroup)' does not exist. Exiting script."
Exit
}
ForEach ($Source in $SourceGroups) {
Get-ADGroupMember -Recursive -Identity $Source | Get-ADUser | Where-Object { $_.Enabled -eq $true } | ForEach-Object {
Add-ADGroupMember -Identity $TargetGroup -Members $_.SamAccountName
}
}
ForEach ($Exclude in $ExcludeGroup) {
If (!(Get-ADGroup -Identity $Exclude | Out-Null))
{
Write-Warning -Message "The AD Group '$($Exclude)' does not exist. Skipping."
Continue
}
Get-ADGroupMember -Recursive -Identity $Exclude | ForEach-Object {
Remove-ADGroupMember -Identity $TargetGroup -Members $_.SamAccountName -Confirm:$false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment