使用c# BCD WMI提供程序来安全启动Windows

本文关键字:安全 启动 Windows 程序 BCD WMI 使用 | 更新日期: 2023-09-27 18:17:48

我已经在网上搜索了如何使用c#安全启动Windows的解决方案。从Vista及以上版本开始,安全启动由BCD控制。当然你可以使用命令行工具"bcdedit":

bcdedit /set {current} safeboot Minimal

但是我不想使用这种方法。所以我的问题是:

如何使用c#重新启动到安全模式?

我已经看了这篇文章,这让我开始了。但我仍然缺少这个谜题的一部分。

非常感谢任何帮助。=)

BCD WMI Provider Reference没有什么帮助

使用c# BCD WMI提供程序来安全启动Windows

我在c#中编写了以下代码,它应该允许您设置安全启动值并删除该值:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
namespace EditBcdStore
{
    public class BcdStoreAccessor
    {
        public const int BcdOSLoaderInteger_SafeBoot = 0x25000080;
        public enum BcdLibrary_SafeBoot
        {
            SafemodeMinimal = 0,
            SafemodeNetwork = 1,
            SafemodeDsRepair = 2
        }
        private ConnectionOptions connectionOptions;
        private ManagementScope managementScope;
        private ManagementPath managementPath;
        public BcdStoreAccessor()
        {
            connectionOptions = new ConnectionOptions();
            connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
            connectionOptions.EnablePrivileges = true;
            managementScope = new ManagementScope("root''WMI", connectionOptions);
            managementPath = new ManagementPath("root''WMI:BcdObject.Id='"{fa926493-6f1c-4193-a414-58f0b2456d1e}'",StoreFilePath='"'"");
        }
        public void SetSafeboot()
        {
            ManagementObject currentBootloader = new ManagementObject(managementScope, managementPath, null);
            currentBootloader.InvokeMethod("SetIntegerElement", new object[] { BcdOSLoaderInteger_SafeBoot, BcdLibrary_SafeBoot.SafemodeMinimal });
        }
        public void RemoveSafeboot()
        {
            ManagementObject currentBootloader = new ManagementObject(managementScope, managementPath, null);
            currentBootloader.InvokeMethod("DeleteElement", new object[] { BcdOSLoaderInteger_SafeBoot });
        }
    }
}

我在我的Surface Pro上测试了一下,它似乎可以工作,可以通过运行以下命令来验证:

bcdedit /enum {current} /v

更新:

上面的代码只是用来设置或删除允许安全引导的值。

执行此操作后,需要重新启动,这也可以使用WMI完成,如下所示:

WMI重新启动远程计算机

答案显示了本地或远程执行此操作的示例。

非常感谢Helen和L-Williams。