Friday, October 23, 2015

Modifying Group Policy with .NET

There is precious little information on programmatic access to Group Policy, and many people say automatic configuration of Group Policy settings can't be done, but it totally can if you put in a little effort.

First, you'll need the Group Policy Management Console class library, which comes with the Group Policy Management Console in Remote Server Administration Tools. Connect to a domain controller by creating a new GPDomain object. Create a new GPO by calling CreateGpo on your GPDomain. To actually get at the policy settings, you'll need to get a ComputerConfiguration object from the Computer property on Gpo, a PolicySettings object from the Policy property on ComputerConfiguration, and a RegistryPolicy object from the GetRegistry function on PolicySettings (not in read-only mode). To get the user policies, use the User property on Gpo instead of Computer.

The methods on RegistryPolicy that start with "Write" allow you to create registry entries that the policy will enforce. When you're finished writing policies, call Save on the RegistryPolicy object with the parameter True if you're updating the computer policy or False if you're updating the user policy. To figure out what entries do what, you'll need the help of policy definitions (ADMX files).

These can be read with ADMX Migrator, and are found in the \Windows\PolicyDefinitions folder on every machine. (The authoritative copy should be on SYSVOL in a domain, but local copies work too.) In ADMX Migrator, right-click "ADMX Templates" in the left pane and choose "Load Template" to open an ADMX file. Browse around the folders until you find the setting you're looking for, and then note the registry key and value that the setting affects. To see what data you should write, check the Values tab. For settings that have extra configuration (beyond Enabled/Disabled), check the Presentation and Value Lists tab.

Microsoft set up a Group Policy search web site/database thing that lets you get the same info, but as of this writing it has some weird behavior with settings that have extra configuration. It does, interestingly, tell you which ADMX file is responsible for each setting, so that could help you even if the value name isn't quite right.

To link (i.e. actually make it have an effect) the GPO to the domain or to an OU, first call GetSom on your GPDomain. GetSom takes the LDAP-style fully-qualified name of the Scope of Management; the DirectoryServices namespace might help you find available SOMs. Call LinkGpo on your Som with the Gpo object and the position at which to insert it; a constant 1 works. The resulting GpoLink object allows you to change the enforcement and enabledness of the GPO. Once that's done, your GPO is linked and in action.

No comments:

Post a Comment