Wednesday, February 13, 2008

Search Active Directory for Deleted Objects in PowerShell function

I was looking around the web for a good way to incorporate a section of code to search for AD deleted objects but came up empty. Off to MSDN I went and found some C# code that did what I wanted. All I needed to do was convert it to Powershell. The code below will search the Deleted Objects container for object that have been deleted the past 60 days. This however can be changed.

   1:  function TombStonedObjects {
   2:      # create Directory Searcher object and set properties to search
   3:      # for tombstoned objects
   5:      $ds = New-Object System.DirectoryServices.DirectorySearcher
   6:      $ds.Tombstone = $TRUE
   7:      $ds.Filter = "isDeleted=TRUE"
   9:      # Query for objects and filter for DN 
  10:      $DSResults=$DS.FindAll()  select path
  12:      # Build simple RegExp to get just Common Name
  13:      $r=[regex]"(?<=CN=).+(?=\\)"
  14:      $DSR2=$DSResults  % { $r.Matches($_);$script:delCount++}
  15:      foreach ($DSobject in $DSR2) { $delMessage += "Deleted object: " + $DSobject.value.trim() + "`n" }
  17:      $delMessage
  19:      # end function
  20:      }

I have this as a function so I can incorporate it into a larger script I have that audits the domain for "ADDED" computer and user objects. I will post that later.

You will also notice a Script Scope Variable named $script:delCount Although in this function it serves no purpose but in the larger domain audit script it will make sense.

No comments: