Compartir a través de


Search for and find a deleted AD object using C#

 

Hi There,

I am Syam Pinnaka, Developer in IAM Services team at Microsoft. In one of my recent projects I had a requirement to search for and restore a deleted AD object. AD Cmdlets provides a means for this using “Get-ADObject” and “Restore-ADObject”. However if you wanted to use these Cmdlets from C# here is how you do it.

  1. Add a reference to below assemblies.

     using System.Management.Automation;
    using System.Management.Automation.Runspaces;
    
     Note: You can get the System.Management.Automation assembly from here.
    
  2. Create an AD run space.

     private static InitialSessionState iss = null;
    private static Runspace myRunSpace = null;
    
    iss = InitialSessionState.CreateDefault();
    iss.ImportPSModule(new string[] { "activedirectory" });
    myRunSpace = RunspaceFactory.CreateRunspace(iss);
    myRunSpace.Open();
    
  3. Create Pipeline.

     Pipeline pipeLine = myRunSpace.CreatePipeline();
    
  4. Build “Get-ADObject” command.

     string filter = "(ObjectClass -eq 'group') -and (" + attributeName + " -like '" + attributeValue + "'" 
    
     + ") -and (isDeleted -eq 'TRUE')";
    
    string domain = “your-domain”;
    
    Command myCommand = new Command("Get-ADObject");
    myCommand.Parameters.Add("Filter", filter);
    myCommand.Parameters.Add("Server", domain);
    myCommand.Parameters.Add("IncludeDeletedObjects");
    
    pipeLine.Commands.Add(myCommand);
    

    Note: The above filter takes AD attributeName and attributeValue to search for an object. Also the above filter is targeted at searching for ‘groups’, if you want to find any object, you can removed this condition from the filter.

  5. Run the command.

     Collection<PSObject> commandResults = pipeLine.Invoke();
    
  6. Capture the results

     if (commandResults.Count > 1)
    {
        throw new Exception("Found more than one deleted group with '" + attributeName + "'='" 
    
     + attributeValue + "' in domain '" + domain + "'");
    }
    
    foreach (PSObject cmdlet in commandResults)
    {
        string cmdletName = cmdlet.BaseObject.ToString();
        System.Diagnostics.Debug.Print(cmdletName);
    
        //do whatever you want with the results.
    }
    
 That’s it and Happy coding! I will show you how to restore a deleted AD object in my next post.

Technorati Tags: .NET,AD