Search code examples
c#gpo

Creating and linking GPO on remote domain controller


I have tried the code below, but it does not work. I've got the exception:

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

on this line:

GPMGPO gpo = (GPMGPO) gpd.CreateGPO();

Here is the actually code:

public void CreateAndLinkGPO()
{
    string strGPO = "Test GPO";
    string strOU = "LDAP://DC=testdc,DC=local";
    GPM gpm = new GPM();
    GPMConstants gpc = (GPMConstants) gpm.GetConstants();
    GPMDomain gpd = (GPMDomain) gpm.GetDomain(Environment.GetEnvironmentVariable("USERDNSDOMAIN"), "", gpc.UseAnyDC);
    GPMSearchCriteria searchOBJ = gpm.CreateSearchCriteria();
    searchOBJ.Add(gpc.SearchPropertyGPODisplayName, gpc.SearchOpEquals, strGPO);
    GPMGPOCollection objGPOlist = gpd.SearchGPOs(searchOBJ);
    GPMSOM gpSom = gpd.GetSOM(strOU);
    GPMGPO gpo = (GPMGPO) gpd.CreateGPO();
    gpSom.CreateGPOLink(-1, objGPOlist[1]);
}

Is there a better way creating and linking a GPO? Because even if this code does work, I still have to install the Remote Server Administration Tools on each server. There are several domains that the application needs to run on.


Solution

  • I have gone the powershell way and everything is working like a champ.

    My intention was to add a certificate to an AD User. But it seems you don't have to do it with GPO. Instead you can do this with powershell commands.

    To create a new AD User, follow this guide:

    Create Active Directory Users PowerShell Script

    To assign a certificate to an existing AD User, follow this guide:

    Set Active Directory “Security Identity Mapping” / “Name Mapping” with C#/Powershell does not add to the right "store"