Other Posts in this Series:
- The Difference Between ADSI and ADSISearcher
- Use ADSI to Check if a User is a Member of an AD Group
- Use ADSI to Check if a Computer is a Member of an AD Group
- Use ADSI to Migrate AD Group Members
- Use ADSI to List Nested Members of an AD Group
This post provides a function which enables us to use ADSI to migrate AD group members. We can also specify whether to copy or move the group members.
function Migrate-ADGroup
{
Param
(
[string]$sourceDN,
[string]$targetDN,
[bool]$move
)
if (!([adsi]::Exists("LDAP://$sourceDN"))) {
write-host "$sourceDN does not exist"
return
}
if (!([adsi]::Exists("LDAP://$targetDN"))) {
write-host "$targetDN does not exist"
return
}
$sourceDNADSI = [ADSI]"LDAP://$sourceDN"
$targetDNADSI = [ADSI]"LDAP://$targetDN"
try {
$sourceDNADSI.member | ForEach-Object {
$groupObject = [adsisearcher]"(distinguishedname=$($_))"
if ($move) {
write-host "Moving $($groupObject.FindOne().Properties.name)"
try { $targetDNADSI.Add("LDAP://$_") } catch {}
try { $sourceDNADSI.Remove("LDAP://$_") } catch {}
} else {
write-host "Copying $($groupObject.FindOne().Properties.name)"
try { $targetDNADSI.Add("LDAP://$_") } catch {}
}
}
} catch {
write-host $_.Exception.Message
}
}
$sourcegroup = "CN=application1,OU=Apps,DC=alkanesolutions,DC=co,DC=uk"
$targetgroup = "CN=application2,OU=Apps,DC=alkanesolutions,DC=co,DC=uk"
#source group to migrate from, target group to migrate to, false (copy members) or true (move members)
Migrate-ADGroup $sourcegroup $targetgroup $false
