C#WUApiLib知道Windows更新是否需要重新启动

时间:2020-09-17 08:02:27

标签: c# .net wuapi

我使用此代码来获取暂挂的Windows更新以及更新的大多数信息:

 static List<PendingUpdate> GetPendingUpdates()
    {
        var updateSession = new UpdateSession();
        var updateSearcher = updateSession.CreateUpdateSearcher();
        updateSearcher.Online = false; //set to true if you want to search online

        List<PendingUpdate> pendingUpdates = new List<PendingUpdate>();
        try
        {
            var searchResult = updateSearcher.Search("IsInstalled=0 And IsHidden=0");
            if (searchResult.Updates.Count > 0)
            {
                Console.WriteLine("There are updates available for installation");

                foreach (IUpdate windowsUpdate in searchResult.Updates)
                {
                    PendingUpdate update = new PendingUpdate();
                    update.Title = windowsUpdate.Title;
                    update.Description = windowsUpdate.Description;
                    update.Downloaded = windowsUpdate.IsDownloaded;
                    update.Urls = new List<string>();
                    foreach (string url in windowsUpdate.MoreInfoUrls)
                    {
                        update.Urls.Add(url);
                    }
                    foreach (dynamic category in windowsUpdate.Categories)
                    {
                        update.Categories += category.Name + ", ";
                    }
                    pendingUpdates.Add(update);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("ERROR");
            throw ex;
        }

        return pendingUpdates;
    }

我还使用此代码来了解计算机当前是否需要重新启动才能完成已安装的更新:

 static bool needsRestart()
    {
        ISystemInformation systemInfo = new SystemInformation();
        return systemInfo.RebootRequired;
    }

现在我的问题是,是否有可能知道是否有待处理的更新需要计算机重新启动才能完成?在第一个代码中,我得到了IUpdate object,但是在安装此更新后,没有看到有关需要重新启动的信息。我有办法获取这些信息吗?

1 个答案:

答案 0 :(得分:0)

对于异步安装,我使用了这样的东西:

rebootRequired = false;

UpdateSession updateSession = new UpdateSession();
updateSession.ClientApplicationID = SusClientID;

IUpdateInstaller updatesInstaller = updateSession.CreateUpdateInstaller();
IInstallationJob job = updatesInstaller.BeginInstall(InstallProgressCallback, installComplete, installState);

// here is your installer code and the checking if the installation is completed

IInstallationProgress jobProgress = job.GetProgress();

for (int updateindex = 0; updateindex < updatesInstaller.Updates.Count; updateindex++)
{
    IUpdateInstallationResult updateInstallResult = jobProgress.GetUpdateResult(updateindex);

    rebootRequired |= updateInstallResult.RebootRequired;
}

if(rebootRequired)
{
    // any of the updates need a reboot
}