如何以编程方式将 GPO 设置为未配置或禁用

2023-11-24

我正在寻找一种编程解决方案,其效果与在 GPOE 中设置“配置 Windows NTP 客户端”状态相同Administrative Templates > System > Windows Time Service > Time Providers > Configure Windows NTP Client to Not Configured or Disabled,但我会在这一点上寻求任何我能得到的帮助。

是否有可以使用 .NET 注册表类修改的注册表项或可以使用 RSoP WMI 类修改的属性?我已经在这两个地方寻找了好几天了,但没有找到任何可以有效禁用 GPO 或具有与禁用或将其设置为相同效果的内容Not Configured在图形用户界面中。


首先,您必须找到要编辑的注册表值。它们都列在 XLS 文档中,可从以下位置下载:http://www.microsoft.com/en-us/download/details.aspx?id=25250。该文档没有指示值的类型(REGSZ、DWORD 等),因此您必须使用编辑器进行设置,然后使用 regedit 查看值的类型。

现在您已经有了注册表项、值名称及其类型,让我们添加一些 C# 并使用 COM 接口组策略对象

[ComImport, Guid("EA502722-A23D-11d1-A7D3-0000F87571E3")]
internal class GPClass
{
}

[ComImport, Guid("EA502723-A23D-11d1-A7D3-0000F87571E3"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IGroupPolicyObject
{
    uint New([MarshalAs(UnmanagedType.LPWStr)] string domainName, [MarshalAs(UnmanagedType.LPWStr)] string displayName, uint flags);

    uint OpenDSGPO([MarshalAs(UnmanagedType.LPWStr)] string path, uint flags);

    uint OpenLocalMachineGPO(uint flags);

    uint OpenRemoteMachineGPO([MarshalAs(UnmanagedType.LPWStr)] string computerName, uint flags);

    uint Save([MarshalAs(UnmanagedType.Bool)] bool machine, [MarshalAs(UnmanagedType.Bool)] bool add, [MarshalAs(UnmanagedType.LPStruct)] Guid extension, [MarshalAs(UnmanagedType.LPStruct)] Guid app);

    uint Delete();

    uint GetName([MarshalAs(UnmanagedType.LPWStr)] StringBuilder name, int maxLength);

    uint GetDisplayName([MarshalAs(UnmanagedType.LPWStr)] StringBuilder name, int maxLength);

    uint SetDisplayName([MarshalAs(UnmanagedType.LPWStr)] string name);

    uint GetPath([MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int maxPath);

    uint GetDSPath(uint section, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int maxPath);

    uint GetFileSysPath(uint section, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int maxPath);

    uint GetRegistryKey(uint section, out IntPtr key);

    uint GetOptions(out uint options);

    uint SetOptions(uint options, uint mask);

    uint GetType(out IntPtr gpoType);

    uint GetMachineName([MarshalAs(UnmanagedType.LPWStr)] StringBuilder name, int maxLength);

    uint GetPropertySheetPages(out IntPtr pages);
}


public enum GroupPolicySection
{
    Root = 0,
    User = 1,
    Machine = 2,
}

public abstract class GroupPolicyObject
{
    protected const int MaxLength = 1024;

    /// <summary>
    /// The snap-in that processes .pol files
    /// </summary>
    private static readonly Guid RegistryExtension = new Guid(0x35378EAC, 0x683F, 0x11D2, 0xA8, 0x9A, 0x00, 0xC0, 0x4F, 0xBB, 0xCF, 0xA2);

    /// <summary>
    /// This application
    /// </summary>
    private static readonly Guid LocalGuid = new Guid(GetAssemblyAttribute<GuidAttribute>(Assembly.GetExecutingAssembly()).Value);

    protected IGroupPolicyObject Instance = null;

    static T GetAssemblyAttribute<T>(ICustomAttributeProvider assembly) where T : Attribute
    {
        object[] attributes = assembly.GetCustomAttributes(typeof(T), true);
        if (attributes.Length == 0)
            return null;

        return (T)attributes[0];
    }

    internal GroupPolicyObject()
    {
        Instance = GetInstance();
    }

    public void Save()
    {
        var result = Instance.Save(true, true, RegistryExtension, LocalGuid);
        if (result != 0)
        {
            throw new Exception("Error saving machine settings");
        }

        result = Instance.Save(false, true, RegistryExtension, LocalGuid);
        if (result != 0)
        {
            throw new Exception("Error saving user settings");
        }
    }

    public void Delete()
    {
        var result = Instance.Delete();
        if (result != 0)
        {
            throw new Exception("Error deleting the GPO");
        }
        Instance = null;
    }

    public RegistryKey GetRootRegistryKey(GroupPolicySection section)
    {
        IntPtr key;
        var result = Instance.GetRegistryKey((uint)section, out key);
        if (result != 0)
        {
            throw new Exception(string.Format("Unable to get section '{0}'", Enum.GetName(typeof(GroupPolicySection), section)));
        }

        var handle = new SafeRegistryHandle(key, true);
        return RegistryKey.FromHandle(handle, RegistryView.Default);
    }

    public abstract string GetPathTo(GroupPolicySection section);

    protected static IGroupPolicyObject GetInstance()
    {
        var concrete = new GPClass();
        return (IGroupPolicyObject)concrete;
    }
}

public class GroupPolicyObjectSettings
{
    public readonly bool LoadRegistryInformation;
    public readonly bool Readonly;

    public GroupPolicyObjectSettings(bool loadRegistryInfo = true, bool readOnly = false)
    {
        LoadRegistryInformation = loadRegistryInfo;
        Readonly = readOnly;
    }

    private const uint RegistryFlag = 0x00000001;
    private const uint ReadonlyFlag = 0x00000002;

    internal uint Flag
    {
        get
        {
            uint flag = 0x00000000;
            if (LoadRegistryInformation)
            {
                flag |= RegistryFlag;
            }

            if (Readonly)
            {
                flag |= ReadonlyFlag;
            }

            return flag;
        }
    }
}

public class ComputerGroupPolicyObject : GroupPolicyObject
{
    public readonly bool IsLocal;

    public ComputerGroupPolicyObject(GroupPolicyObjectSettings options = null)
    {
        options = options ?? new GroupPolicyObjectSettings();
        var result = Instance.OpenLocalMachineGPO(options.Flag);
        if (result != 0)
        {
            throw new Exception("Unable to open local machine GPO");
        }
        IsLocal = true;
    }

    public ComputerGroupPolicyObject(string computerName, GroupPolicyObjectSettings options = null)
    {
        options = options ?? new GroupPolicyObjectSettings();
        var result = Instance.OpenRemoteMachineGPO(computerName, options.Flag);
        if (result != 0)
        {
            throw new Exception(string.Format("Unable to open GPO on remote machine '{0}'", computerName));
        }
        IsLocal = false;
    }

    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;
    }

    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;
    }

    private static string Key(string registryInformation, out string value, out GroupPolicySection section)
    {
        // Parse parameter of format HKCU\Software\Policies\Microsoft\Windows\Personalization!NoChangingSoundScheme
        string[] split = registryInformation.Split('!');
        string key = split[0];
        string hive = key.Substring(0, key.IndexOf('\\'));
        key = key.Substring(key.IndexOf('\\') + 1);

        value = split[1];

        if (hive.Equals(@"HKLM", StringComparison.OrdinalIgnoreCase)
            || hive.Equals(@"HKEY_LOCAL_MACHINE", StringComparison.OrdinalIgnoreCase))
        {
            section = GroupPolicySection.Machine;
        }
        else
        {
            section = GroupPolicySection.User;
        }
        return key;
    }

    /// <summary>
    ///     Retrieves the file system path to the root of the specified GPO section.
    ///     The path is in UNC format.
    /// </summary>
    public override string GetPathTo(GroupPolicySection section)
    {
        var sb = new StringBuilder(MaxLength);
        var result = Instance.GetFileSysPath((uint)section, sb, MaxLength);
        if (result != 0)
        {
            throw new Exception(string.Format("Unable to retrieve path to section '{0}'", Enum.GetName(typeof(GroupPolicySection), section)));
        }

        return sb.ToString();
    }
}

以及如何使用它:

static void Main(string[] args)
{
    ComputerGroupPolicyObject.SetPolicySetting(@"HKLM\Software\Policies\Microsoft\Windows\HomeGroup!DisableHomeGroup", "0", RegistryValueKind.DWord);
    ComputerGroupPolicyObject.SetPolicySetting(@"HKLM\Software\Policies\Microsoft\Windows\HomeGroup!DisableHomeGroup", "1", RegistryValueKind.DWord);
    ComputerGroupPolicyObject.SetPolicySetting(@"HKLM\Software\Policies\Microsoft\Windows\HomeGroup!DisableHomeGroup", null, RegistryValueKind.Unknown);
}

代码灵感来自https://bitbucket.org/MartinEden/local-policy

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何以编程方式将 GPO 设置为未配置或禁用 的相关文章

  • ComboBox DataBinding 导致 ArgumentException

    我的几个类对象 class Person public string Name get set public string Sex get set public int Age get set public override string
  • 如何在C(Linux)中的while循环中准确地睡眠?

    在 C 代码 Linux 操作系统 中 我需要在 while 循环内准确地休眠 比如说 10000 微秒 1000 次 我尝试过usleep nanosleep select pselect和其他一些方法 但没有成功 一旦大约 50 次 它
  • 查找进程的完整路径

    我已经编写了 C 控制台应用程序 当我启动应用程序时 不使用cmd 我可以看到它列在任务管理器的进程列表中 现在我需要编写另一个应用程序 在其中我需要查找以前的应用程序是否正在运行 我知道应用程序名称和路径 所以我已将管理对象搜索器查询写入
  • 函数参数的默认参数是否被视为该参数的初始值设定项?

    假设我有这样的函数声明 static const int R 0 static const int I 0 void f const int r R void g int i I 根据 dcl fct default 1 如果在参数声明中指
  • 当一组凭据下的计划任务启动的进程在另一组凭据下运行另一个程序时,Windows 是否有限制

    所以我有一个简单的例子 其中我有应用程序 A 它对用户 X 本地管理员 有一些硬编码的凭据 然后它使用硬编码的绝对路径启动带有这些凭据的应用程序 B A 和 B 以及 dotnet 控制台应用程序 但是它们不与控制台交互 只是将信息写入文件
  • 查看 NuGet 包依赖关系层次结构

    有没有一种方法 文本或图形 来查看 NuGet 包之间的依赖关系层次结构 如果您使用的是新的 csproj 您可以在此处获取所有依赖项 在项目构建后 项目目录 obj project assets json
  • 在Linux中,找不到框架“.NETFramework,Version=v4.5”的参考程序集

    我已经设置了 Visual studio 来在我的 Ubuntu 机器上编译 C 代码 我将工作区 我的代码加载到 VS 我可以看到以下错误 The reference assemblies for framework NETFramewo
  • 为什么可以通过ref参数修改readonly字段?

    考虑 class Foo private readonly string value public Foo Bar ref value private void Bar ref string value value hello world
  • 使用valgrind进行GDB远程调试

    如果我使用远程调试gdb我连接到gdbserver using target remote host 2345 如果我使用 valgrind 和 gdb 调试内存错误 以中断无效内存访问 我会使用 target remote vgdb 启动
  • 如何在 Qt 应用程序中通过终端命令运行分离的应用程序?

    我想使用命令 cd opencv opencv 3 0 0 alpha samples cpp cpp example facedetect lena jpg 在 Qt 应用程序中按钮的 clicked 方法上运行 OpenCV 示例代码
  • IQueryable 单元或集成测试

    我有一个 Web api 并且公开了一个端点 如下所示 api 假期 name name 这是 Web api 的控制器 get 方法 public IQueryable
  • 保护 APK 中的字符串

    我正在使用 Xamarin 的 Mono for Android 开发一个 Android 应用程序 我目前正在努力使用 Google Play API 添加应用内购买功能 为此 我需要从我的应用程序内向 Google 发送公共许可证密钥
  • 等待 IAsyncResult 函数直至完成

    我需要创建等待 IAsyncResult 方法完成的机制 我怎样才能做到这一点 IAsyncResult result contactGroupServices BeginDeleteContact contactToRemove Uri
  • WPF DataGridTemplateColumn 组合框更新所有行

    我有这个 XAML 它从 ItemSource 是枚举的组合框中选择一个值 我使用的教程是 http www c sharpcorner com uploadfile dpatra combobox in datagrid in wpf h
  • 打印大型 WPF 用户控件

    我有一个巨大的数据 我想使用 WPF 打印 我发现WPF提供了一个PrintDialog PrintVisual用于打印派生的任何 WPF 控件的方法Visual class PrintVisual只会打印一页 因此我需要缩放控件以适合页面
  • C++ new * char 不为空

    我有一个问题 我在 ASIO 中开发服务器 数据包采用尖头字符 当我创建新字符时 例如char buffer new char 128 我必须手动将其清理为空 By for int i 0 i lt 128 i buffer i 0x00
  • 将数组作为参数传递

    如果我们修改作为方法内参数传递的数组的内容 则修改是在参数的副本而不是原始参数上完成的 因此结果不可见 当我们调用具有引用类型参数的方法时 会发生什么过程 这是我想问的代码示例 using System namespace Value Re
  • 如何在richtextbox中使用多颜色[重复]

    这个问题在这里已经有答案了 我使用 C windows 窗体 并且有 richtextbox 我想将一些文本设置为红色 一些设置为绿色 一些设置为黑色 怎么办呢 附图片 System Windows Forms RichTextBox有一个
  • 如何使用 C++11 using 语法键入定义函数指针?

    我想写这个 typedef void FunctionPtr using using 我该怎么做呢 它具有类似的语法 只不过您从指针中删除了标识符 using FunctionPtr void 这是一个Example http ideone
  • OpenCV SIFT 描述符关键点半径

    我正在深入研究OpenCV的SIFT描述符提取的实现 https github com Itseez opencv blob master modules nonfree src sift cpp 我发现了一些令人费解的代码来获取兴趣点邻域

随机推荐