public static object GetPolicySetting(string registryInformation) { string valueName; GroupPolicySection section; string key = Key(registryInformation, out valueName, out section); // Thread must be STA object result = null; var t = new Thread(() => { var gpo = new ComputerGroupPolicyObject(); using (RegistryKey rootRegistryKey = gpo.GetRootRegistryKey(section)) { // Data can't be null so we can use this value to indicate key must be delete using (RegistryKey subKey = rootRegistryKey.OpenSubKey(key, true)) { if (subKey == null) { result = null; } else { result = subKey.GetValue(valueName); } } } }); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); return(result); }
static void Main(string[] args) { /* ComputerGroupPolicyObject.SetPolicySetting(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate!WUServer", "http://10.160.5.20:8531", RegistryValueKind.String); * ComputerGroupPolicyObject.SetPolicySetting(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate!WUStatusServer", "http://10.160.5.20:8531", RegistryValueKind.String); * ComputerGroupPolicyObject.SetPolicySetting(@"HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU!UseWUServer", "1", RegistryValueKind.DWord); */ ComputerGroupPolicyObject.SetPolicySetting(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer!NoDriveTypeAutoRun", "255", RegistryValueKind.DWord); // start gpedit.msc for the changes to take effects Process p = Process.Start("gpedit.msc"); if (p.WaitForInputIdle()) { try { p.CloseMainWindow(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { p.Kill(); } } }
public static void SetPolicySetting(string registryInformation, string settingValue, RegistryValueKind registryValueKind) { string valueName; GroupPolicySection section; string key = Key(registryInformation, out valueName, out section); // Thread must be STA Exception exception = null; var t = new Thread(() => { try { var gpo = new ComputerGroupPolicyObject(); using (RegistryKey rootRegistryKey = gpo.GetRootRegistryKey(section)) { // Data can't be null so we can use this value to indicate key must be delete if (settingValue == null) { using (RegistryKey subKey = rootRegistryKey.OpenSubKey(key, true)) { if (subKey != null) { subKey.DeleteValue(valueName); } } } else { using (RegistryKey subKey = rootRegistryKey.CreateSubKey(key)) { subKey.SetValue(valueName, settingValue, registryValueKind); } } } gpo.Save(); } catch (Exception ex) { exception = ex; } }); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); if (exception != null) { throw exception; } }