PowerShell Script to Copy Members of One Group to Another

#Author: Kim Doan
#Please tell me this code suck so that I can improve # Adding Prerequisite Active Directory Module
if ( !(get-module -name "ActiveDirectory") ) {"ActiveDirectory module not in shell environment. Now importing..."; Add-WindowsFeature RSAT-AD-PowerShell; import-module -name "ActiveDirectory" -DisableNameChecking | out-null } Do{ $fromGroup = Read-Host -Prompt 'Copy From Group:' $toGroup = Read-Host -Prompt 'Copy To Group:' # This convoluted code is to be backward compatible with older PowerShell versions $oldMembers=(Get-ADGroupMember -Identity $fromGroup -Recursive); $newMembers=(Get-ADGroupMember -Identity $toGroup -Recursive); $old=@(); $new=@(); $index=0; foreach ($newMember in $newMembers){$new+=,$newMember.name} foreach ($oldMember in $oldMembers){$old+=,$oldMember.name} foreach ($o in $old){ if ($new -contains $o){#Do nothing#"$o already exists at the destination";} else { Add-ADGroupMember -Identity $toGroup -Members $oldMembers[$index]; "New entry '$o' from '$fromGroup' has been copied to the group '$toGroup'"; } $index+=1; } $flag = Read-Host -Prompt 'Press Any Key = exit; C = Continue Copying...'} while ($flag -match '[Cc]')

Leave a Reply

Your email address will not be published. Required fields are marked *