Search code examples
c#hyperlinkgpoou

C#, Create GPO And link it to OU using Microsoft.GroupPolicy.Management?


I've done hard research and trying to solve my problem. 3 days googling and asking now i ended up with this :

using Microsoft.GroupPolicy;

private void ManipulateGPO(){
    GPDomain domain = new GPDomain("sh.dom");
    Gpo gpo_background = domain.CreateGpo("testingGPO");
}

the code above create a GPO successfully. but i need to link it to an OU?

any help will be appreciated.

UPDATE 1: My GPO Screenshot


Solution

  • You use the SOM (Scope of Management) class to link to the OU

    using Microsoft.GroupPolicy;
    
    private void ManipulateGPO(){
        GPDomain domain = new GPDomain("sh.dom");
        Gpo gpo_background = domain.CreateGpo("testingGPO");
        Som som = domain.GetSom("The path of the SOM specified as a fully qualified distinguished name, for example, (ou=MyOU,dc=contoso,dc=com)");
        som.LinkGpo(-1, gpo_background);
    }
    

    References Som Class: https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.grouppolicy.som(v=vs.85).aspx

    LinkGpo: https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.grouppolicy.som.linkgpo(v=vs.85).aspx

    GPDomain.GetSom: https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.grouppolicy.gpdomain.getsom(v=vs.85).aspx