Freigeben über


Searching for Deleted Objects using Powershell

 

This question popped in my mailbox – how can you use a script to search for deleted objects in the Active Directory, just as described here - http://support.microsoft.com/kb/258310.

Well, obviously you can’t script ldp.exe, so the second option was to use ADSI objects. The problem with those is that I couldn’t find anyway of using server controls which are required in our case (OID

1.2.840.113556.1.4.417 is required to return deleted objects).

So I ended up using the System.DirectoryServices.Protocols namespace in Powershell in order to get the job done. So here it is:

 [Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.Protocols")
$rootDSE = [adsi]"LDAP://RootDSE"

$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($rootDSE.dnsHostName)
$request = New-Object System.directoryServices.Protocols.SearchRequest($rootDSE.Properties["defaultNamingContext"].Value.ToString(), "(isDeleted=TRUE)", "Subtree")

$control = New-Object System.DirectoryServices.Protocols.ShowDeletedControl

$request.Controls.Add($control)

$response = $LDAPConnection.SendRequest($request)

$response.Entries | %{

$_.distinguishedName; 

if($_.attributes.samaccountname -ne $null)
{
 write-host "SamAccountName:" $_.attributes.samaccountname[0]}
}

-Michael

Comments

  • Anonymous
    December 23, 2010
    Or the following :) $searcher = New-Object System.DirectoryServices.DirectorySearcher -Property @{ Filter = '(&(isDeleted=TRUE))'; Tombstone = $true} $searcher.Findall() | Foreach-Object {$_.properties['samaccountname']} -Shay http://PowerShay.com