Sometime we or others delete items that were not meant to be deleted.
We all make mistakes.
Case in point, deleting an object from Active Directory. This happens more often than you think, however, if your organization has deployed Windows Server 2012R2 or newer, you have the ability to enable the Active Directory Recycle Bin. Steps to enable the Active Directory Recycle Bin can be viewed here:
Once enabled, recovery of said deleted item in Active Directory can quickly be enabled by using the following script to recover a user based on username:
|1:||$dn = (Get-ADObject -SearchBase (get-addomain).deletedobjectscontainer -IncludeDeletedObjects -filter “samaccountname -eq ‘$Username'”).distinguishedname|
|2:||Restore-ADObject -identity $dn|
The first line retrieves the deleted user’s DistinguishedName. Notice that the DN changes when a user gets deleted as it is now located in the Recycle Bin. The deleted objects container can easily be found using the (Get-ADDomain).DeletedObjectsContainer part found in line 1. This line searches for AD objects located in the deleted objects container whose username matches the one that was deleted. The -IncludeDeletedObjects flag also needs to be set or nothing deleted will be returned.
The second line uses the Restore-ADObject cmdlet to restore the object found at the DN.