Comparer l’appartenance des groupes AD entre 2 comptes

Ce document décrit le script qui permet de comparer 2 comptes AD afin de calquer les appartenances.

Pre-requis
exécution des scripts powershell
droit de modification de comptes AD

Le script

Param(
<pre>    $sourceacc, 
    $destacc, 
    [switch]$noconfirm 
) 
 
# Checks if both accounts are provided as an argument, otherwise prompts for input 
if (-not $sourceacc) { $sourceacc = read-host "Please input source user name, the user the rights will be read from" } 
if (-not $destacc) { $destacc = read-host "Please input destination user name, the user which will be added to the groups of the source user" } 
 
# Retrieves the group membership for both accounts 
$sourcemember = get-aduser -filter {samaccountname -eq $sourceacc} -property memberof | select memberof 
$destmember = get-aduser -filter {samaccountname -eq $destacc} -property memberof | select memberof 
 
# Checks if accounts have group membership, if no group membership is found for either account script will exit 
if ($sourcemember -eq $null) {"Source user not found";return} 
if ($destmember -eq $null) {"Destination user not found";return} 
 
# Checks for differences, if no differences are found script will prompt and exit 
if (-not (compare-object $destmember.memberof $sourcemember.memberof | where-object {$_.sideindicator -eq '=>'})) {write-host "No difference between $sourceacc & $destacc groupmembership found. $destacc will not be added to any additional groups.";return} 
 
# Routine that changes group membership and displays output to prompt 
compare-object $destmember.memberof $sourcemember.memberof | where-object {$_.sideindicator -eq '=>'} | 
    select -expand inputobject | foreach {write-host "$destacc will be added to:"([regex]::split($_,'^CN=|,OU=.+$'))[1]} 
 
# If no confirmation parameter is set no confirmation is required, otherwise script will prompt for confirmation 
if ($noconfirm)    { 
    compare-object $destmember.memberof $sourcemember.memberof | where-object {$_.sideindicator -eq '=>'} |  
        select -expand inputobject | foreach {add-adgroupmember "$_" $destacc} 
} 
 
else { 
    do{ 
        $UserInput = Read-Host "Are you sure you wish to add $destacc to these groups?`n[Y]es, [N]o or e[X]it" 
        if (("Y","yes","n","no","X","exit") -notcontains $UserInput) { 
            $UserInput = $null 
            Write-Warning "Please input correct value" 
        } 
        if (("X","exit","N","no") -contains $UserInput) { 
            Write-Host "No changes made, exiting..." 
            exit 
        }      
        if (("Y","yes") -contains $UserInput) { 
            compare-object $destmember.memberof $sourcemember.memberof | where-object {$_.sideindicator -eq '=>'} |  
                select -expand inputobject | foreach {add-adgroupmember "$_" $destacc} 
        } 
    } 
    until ($UserInput -ne $null) 
}

Utilisation du script

activer le module ActiveDirectory

Import-Module activedirectory

lancer le script

.\Compare-ADuserAddGroup.ps1
Please input source user name, the user the rights will be read from: user1
Please input destination user name, the user which will be added to the groups of the source user: user2
pruban will be added to: Group ABC 1
pruban will be added to: Group ABC 2
pruban will be added to: Group ABC 36dfa920
pruban will be added to: Group ABC 43
pruban will be added to: Group ABC 42
pruban will be added to: Group ABC 45
pruban will be added to: Group ABC 543
pruban will be added to: Group ABC 45
pruban will be added to: Group ABC 34

Are you sure you wish to add user2 to these groups?
[Y]es, [N]o or e[X]it: Y

source:http://gallery.technet.microsoft.com/scriptcenter/Compare-group-membership-36dfa920

Configurer et Utiliser la poubelle AD

La poubelle AD est une fonctionnalite de DS depuis 2008R2 (peut etre 2012?). Ceci permet de restorer des objets sans perdre les attributs – comme avec adrestore de sysinternals.

Activer la poubelle AD

Enable-ADOptionalFeature –Identity ‘Recycle Bin Feature’ –Scope  ForestOrConfigurationSet –Target ‘domain.local’
WARNING: Enabling 'Recycle Bin Feature' on 'CN=Partitions,CN=Configuration,DC=domain,DC=local' is an irreversible action!
You will not be able to disable 'Recycle Bin Feature' on 'CN=Partitions,CN=Configuration,DC=domain,DC=local' if you proceed.

Confirm
Are you sure you want to perform this action?
Performing operation &quot;Enable&quot; on Target &quot;Recycle Bin Feature&quot;.
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is &quot;Y&quot;):

Configurer la poubelle

Trouver la valeur de retention courante:

dsquery * &quot; cn=Directory Service,cn=Windows NT,cn=Services,cn=Configuration,dc=domain,dc=local&quot; -scope base -attr tombstonelifetime
tombstonelifetime
180

Pour modifier cette valeur, il faut utiliser ADSIedit (dans le contexte Configuration aka LDAP://DC.domain.local/Configuration) et naviguer vers CN=Services,CN=Windows NT, CN=Directory Service tombstonelifetime.

Ces objets sont conservés dans un container de la base AD secret. Et comme l’idee est de pouvoir les restorer voyons comme on peut faire.

Le container des objets se trouve en ici:

 Get-ADDomain | select DeletedObjectsContainer DeletedObjectsContainer
-----------------------
CN=Deleted Objects,DC=domain,DC=local 

Lister les objets effacés
On doit utiliser la commande get-adobject avec le parametre -IncludeDeletedObjects

 get-adobject -filter 'objectclass -eq "user1" -AND IsDeleted -eq $True' -IncludeDeletedObjects -properties IsDeleted,LastKnownParent

Deleted           : True
DistinguishedName : CN=zzz_user1\0ADEL:1a354486-8aeb-4f5f-8d72-33aab18125bf,CN=Deleted Objects,DC=domain,DC=local
IsDeleted         : True
LastKnownParent   : OU=Désactivés,OU=cie,DC=domain,DC=local
Name              : zzz_user1
DEL:1a354486-8aeb-4f5f-8d72-33aab18125bf
ObjectClass       : user
ObjectGUID        : 1a354486-8aeb-4f5f-8d72-33aab18125bf

On peut aussi lister un utilisateur en particulier en utilisant les paramètres de filtrage

get-adobject -filter 'Name -like "*user2*" -AND IsDeleted -eq $True' -IncludeDeletedObjects -Properties samaccountname

Deleted           : True
DistinguishedName : CN=zzz_user2\0ADEL:3bea71e0-e5c0-41a
a-9b18-85abaaff4667,CN=Deleted Objects,DC=domain,DC=local
Name              : zzz_user2
DEL:3bea71e0-e5c0-41aa-9b18-85abaaff4667
ObjectClass       : user
ObjectGUID        : 3bea71e0-e5c0-41aa-9b18-85abaaff4667
samaccountname    : user2

Restorer un objet effacé

Une fois trouver en listant avec get-adobject, la commande restore-adobject peut faire un test ou restorer l’object directement.

Pour faire un test, on utilise -WhatIf

get-adobject -filter 'Name -like "*user2*"' -IncludeDeletedObjects | Restore-ADObject -WhatIf
WhatIf : Opération « Restore » en cours sur la cible « CN=zzz_user2\0ADEL:3bea71e0-e5c0-41aa-9b18-85abaaff4667,CN=Deleted Objects,DC=domain,DC=local ».

Pour restorer, on utilise -PassThru

get-adobject -filter 'Name -like "*user2*"' -IncludeDeletedObjects | Restore-ADObject -PassThru

DistinguishedName   Name                ObjectClass         ObjectGUID
-----------------   ----                -----------         ----------
cn=user2 ... zzz_user2 ... user                3bea71e0-e5c0-41...

On vérifie si le compte a ete restore

 get-aduser -filter 'Name -like "*user2*"'
DistinguishedName : CN=zzz_user2
Nicol,OU=Désactivés,OU=user,DC=domain,DC=local
Enabled           : False
GivenName         : zzz_user2
Name              : zzz_user2
ObjectClass       : user
ObjectGUID        : 3bea71e0-e5c0-41aa-9b18-85abaaff4667
SamAccountName    : user2
SID               : S-1-5-21-1069915444-1557172909-2421692447-1258
Surname           : user2
UserPrincipalName : user2@domain.local

Si on ne veut pas que les objets soient restores au même endroit, on peut utiliser l’option -TargetPath “DN path”