次の方法で共有


Restore a deleted AD object using C#

Hi There,

I am Syam Pinnaka, Developer in IAM Services team at Microsoft.

In the last post we have seen how to search for and find a deleted AD Object. In this post let’s see how to restored a deleted AD Object using “Restore-ADObject” Cmdlet and C#.

  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” and “Restore-ADObject” commands.

     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.
    
    Command restoreCommand = new Command("Restore-ADObject");
    pipeLine.Commands.Add(restoreCommand);
    
  5. Run the command.

     Collection<PSObject> commandResults = pipeLine.Invoke();
    
  6.  Capture the results.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!

Technorati Tags: AD,.NET,Cmdlet

Comments