0

I'm searching for a way to list all GPOs applied (linked and inherited) to a specific OU through code.

I know there is an attribute representing the linked GPOs called GPLink, but it only gives the directly linked ones.

I searched google and found there is a gpmgmt COM object but I couldn't understand how to use it for my purpose and if it even possible.

Thanks for any help.

Terry Gardner
  • 10,957
  • 2
  • 28
  • 38
ronlut
  • 572
  • 5
  • 17

2 Answers2

1

I have the following sub to share. It doesn't list the names of the GPOs but returns the count. A minor mod will allow you to get the names (check out the properties of GPOLink in the foreach loop). You will need to have GPMC installed and gpmgmt.dll added as a project reference.

 private string getGPOLinkCount(string OUPathDN, bool onlyEnabledLinks, bool includeInheritedLinks)
    {
        int linkCount = 0;

        try
        {
            GPMGMTLib.GPM gpm = new GPMGMTLib.GPM();
            GPMGMTLib.IGPMConstants gpc = gpm.GetConstants();
            GPMGMTLib.IGPMDomain gpd = gpm.GetDomain(Environment.GetEnvironmentVariable("USERDNSDOMAIN"), "", gpc.UseAnyDC);

            GPMGMTLib.GPMSOM gpSom = gpd.GetSOM(OUPathDN);

            GPMGPOLinksCollection GPOLinks = gpSom.GetGPOLinks();
            GPMGPOLinksCollection GPOLinksIncludingInherited = gpSom.GetInheritedGPOLinks();


            if (!includeInheritedLinks)
            {
                foreach (GPMGPOLink GPOLink in GPOLinks)
                {
                    if (onlyEnabledLinks)
                    {
                        if (GPOLink.Enabled)
                        {
                            linkCount++;
                        }
                    }
                    if (!onlyEnabledLinks) //Get all links, disabled or enabled
                    {
                        linkCount++;
                    }
                }                   
            }

            if (includeInheritedLinks)
            {
                foreach (GPMGPOLink GPOLink in GPOLinksIncludingInherited)
                {
                    if (onlyEnabledLinks)
                    {
                        if (GPOLink.Enabled)
                        {
                            linkCount++;
                        }
                    }
                    if (!onlyEnabledLinks) //Get all links, disabled or enabled
                    {
                        linkCount++;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            return "GPO links: " + ex.Message.Replace("\r\n", "");
        }

        return linkCount.ToString();            
    }
NadimAJ
  • 137
  • 1
  • 13
0

You would need to iterate upwards through each parent of the given OU until you reach the domain head.

Brian Desmond
  • 4,473
  • 1
  • 13
  • 11