public void InstallPatches() { Log("Searching for updates..."); List<IUpdate5> updates; do { UpdateSession session = new UpdateSession(); updates = GetPatches(session); PrintStats(updates); DownloadPatches(session, updates); updates = GetPatches(session); InstallPatches(session, updates); updates = GetPatches(session); } while (updates.Count() > 0); Log("Done!"); return; }
private Task <ISearchResult> SearchUpdatesAsync() { var tcs = new TaskCompletionSource <ISearchResult>(); var updateSession = new UpdateSession(); IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); updateSearcher.Online = false; var callback = new UpdateSearcherCallback(updateSearcher, tcs); try { updateSearcher.BeginSearch("IsInstalled = 0 And IsHidden = 0 And BrowseOnly = 0", callback, null); } catch (OperationCanceledException) { tcs.SetCanceled(); } catch (Exception ex) { tcs.SetException(ex); } return(tcs.Task); }
static void Main(string[] args) { //Type USType = Type.GetTypeFromProgID("Microsoft.Update.Session"); //dynamic updateSession = Activator.CreateInstance(USType); //Type USMType = Type.GetTypeFromProgID("Microsoft.Update.ServiceManager"); //dynamic updateServiceManager = Activator.CreateInstance(USMType); //dynamic updateService = updateServiceManager.AddScanPackageService("Offline Sync Service", "c:\\wsusscn2.cab", 1); //Console.WriteLine("123"); UpdateSession uSession = new UpdateSession(); IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher(); uSearcher.Online = false; try { ISearchResult sResult = uSearcher.Search("IsInstalled=1 And IsHidden=0"); string text = "Found " + sResult.Updates.Count + " updates" + Environment.NewLine; foreach (IUpdate update in sResult.Updates) { text += update.Title + Environment.NewLine; } Console.WriteLine(text); } catch (Exception ex) { Console.WriteLine("Something went wrong: " + ex.Message); } }
protected override int Run() { _loggingFeature.Configure(); if (!(Require(_databaseFeature.Host, "host") && Require(_databaseFeature.Database, "database") && Require("username", _usernamePasswordFeature.Username) && Require("password", _usernamePasswordFeature.Password) && Require(_scriptRoot, "script root directory"))) { return(-1); } try { UpdateSession.ApplyChangeScripts( _databaseFeature.Host, _databaseFeature.Database, _usernamePasswordFeature.Username, _usernamePasswordFeature.Password, _createIfMissing, _scriptRoot, _defineVariablesFeature.Variables); return(0); } catch (Exception ex) { Log.Fatal(ex, "Could not apply change scripts"); return(-1); } }
public void GetWindowsUpdates(StreamWriter writer) { writer.WriteLine("- Windows Update History:"); UpdateSession updateSession = new UpdateSession(); IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); IUpdateHistoryEntryCollection updateHistoryCollection = updateSearcher.QueryHistory(0, updateSearcher.GetTotalHistoryCount()); foreach (IUpdateHistoryEntry updateHistory in updateHistoryCollection) { if (updateHistory.Date == new DateTime(1899, 12, 30)) { continue; } writer.WriteLine("Date: " + updateHistory.Date.ToLongDateString() + " " + updateHistory.Date.ToLongTimeString()); writer.WriteLine("Title: " + (updateHistory.Title != null ? updateHistory.Title : "")); writer.WriteLine("Description: " + (updateHistory.Description != null ? updateHistory.Description : "")); writer.WriteLine("Operation: " + updateHistory.Operation); writer.WriteLine("Result Code: " + updateHistory.ResultCode); writer.WriteLine("Support URL: " + (updateHistory.SupportUrl != null ? updateHistory.SupportUrl : "")); writer.WriteLine("Update ID: " + (updateHistory.UpdateIdentity.UpdateID != null ? updateHistory.UpdateIdentity.UpdateID : "")); writer.WriteLine("Update Revision: " + (updateHistory.UpdateIdentity.RevisionNumber.ToString() != null ? updateHistory.UpdateIdentity.RevisionNumber.ToString() : "")); writer.WriteLine(); } }
public async Task SearchAsyncTest(string criteria) { try { var Session = new UpdateSession(); var Searcher = Session.CreateUpdateSearcher(); Debug.WriteLine("SEARCH START."); var Result = string.IsNullOrEmpty(criteria) ? await Searcher.SearchAsync(TokenSource.Token) : await Searcher.SearchAsync(criteria, TokenSource.Token); Debug.WriteLine("SEARCH STOP."); Debug.WriteLine($"SEARCH RESULT: {ISearchResultToString(Result)}"); Debug.WriteLine("SEARCH RESULT ALL OUTPUT START."); foreach (var Update in Result.Updates.Cast <IUpdate>()) { Debug.WriteLine($"UPDATE: {IUpdateToString(Update)}"); } Debug.WriteLine("SEARCH RESULT ALL OUTPUT STOP."); } catch (COMException e) { var state = e.GetWindowsUpdateHResult(); if (Enum.IsDefined(state.GetType(), state)) { Assert.Fail($"ERROR: {state}(0x{(uint)state:x}) {state.GetDescription()}"); } throw; } }
public void ComparingEntitiesSession() { for (int i = 0; i < 3; i++) { long ts = TimeHelper.UnixTimeNow(); BeginSession bs0 = TestHelper.CreateBeginSession(i, i, ts); BeginSession bs1 = TestHelper.CreateBeginSession(i, i, ts); BeginSession bs2 = TestHelper.CreateBeginSession(i + 1, i, ts); BeginSession bs3 = TestHelper.CreateBeginSession(i, i + 1, ts); Assert.Equal(bs0, bs1); Assert.NotEqual(bs1, bs2); Assert.NotEqual(bs1, bs3); EndSession es0 = TestHelper.CreateEndSession(i, ts); EndSession es1 = TestHelper.CreateEndSession(i, ts); EndSession es2 = TestHelper.CreateEndSession(i + 1, ts); Assert.Equal(es0, es1); Assert.NotEqual(es1, es2); UpdateSession us0 = TestHelper.CreateUpdateSession(i, i, ts); UpdateSession us1 = TestHelper.CreateUpdateSession(i, i, ts); UpdateSession us2 = TestHelper.CreateUpdateSession(i + 1, i, ts); Assert.Equal(us0, us1); Assert.NotEqual(us1, us2); } }
public WuAgent() { mInstance = this; mDispatcher = Dispatcher.CurrentDispatcher; mUpdateDownloader = new UpdateDownloader(); mUpdateDownloader.Finished += DownloadsFinished; mUpdateDownloader.Progress += DownloadProgress; mUpdateInstaller = new UpdateInstaller(); mUpdateInstaller.Finished += InstallFinished; mUpdateInstaller.Progress += InstallProgress; dlPath = Program.appPath + @"\Downloads"; WindowsUpdateAgentInfo info = new WindowsUpdateAgentInfo(); var currentVersion = info.GetInfo("ApiMajorVersion").ToString().Trim() + "." + info.GetInfo("ApiMinorVersion").ToString().Trim() + " (" + info.GetInfo("ProductVersionString").ToString().Trim() + ")"; AppLog.Line("Windows Update Agent Version: {0}", currentVersion); mUpdateSession = new UpdateSession(); mUpdateSession.ClientApplicationID = Program.mName; //mUpdateSession.UserLocale = 1033; // alwys show strings in englisch mUpdateServiceManager = new UpdateServiceManager(); if (MiscFunc.parseInt(Program.IniReadValue("Options", "LoadLists", "0")) != 0) { LoadUpdates(); } }
public static List <string> GetPendingUpdateTitles(int isInstalled) { UpdateSession updateSession = new UpdateSession(); try { Type stype = Type.GetTypeFromProgID("Microsoft.Update.Session"); updateSession = (UpdateSession)Activator.CreateInstance(stype); } catch (COMException ce) { throw ce; } ISearchResult uResult = updateSession .CreateUpdateSearcher() .Search( $"IsInstalled={isInstalled}" + " and " + "IsHidden=0" //+ " and " + //"Type='Software'" ); return((from IUpdate update in uResult.Updates select update.Title).ToList()); //UpdateDownloader downloader = uSession.CreateUpdateDownloader(); //downloader.Updates = uResult.Updates; //downloader.Download(); }
public void InstallPatches() { Log("Searching for updates..."); List <IUpdate5> updates; do { UpdateSession session = new UpdateSession(); updates = GetPatches(session); PrintStats(updates); DownloadPatches(session, updates); updates = GetPatches(session); InstallPatches(session, updates); updates = GetPatches(session); }while (updates.Count() > 0); Log("Done!"); return; }
public void Init() { AppLog.Line(Program.fmt("Windows Update Manager, Version v{0} by David Xanatos", mVersion)); AppLog.Line(Program.fmt("This Tool is Open Source under the GNU General Public License, Version 3\r\n")); mUpdateSession = new UpdateSession(); mUpdateSession.ClientApplicationID = "Windows Update Manager"; mUpdateServiceManager = new UpdateServiceManager(); foreach (IUpdateService service in mUpdateServiceManager.Services) { if (service.Name == "Offline Sync Service") { mUpdateServiceManager.RemoveService(service.ServiceID); } else { mServiceList.Add(service.Name); } } mUpdateSearcher = mUpdateSession.CreateUpdateSearcher(); int count = mUpdateSearcher.GetTotalHistoryCount(); mUpdateHistory = mUpdateSearcher.QueryHistory(0, count); WindowsUpdateAgentInfo info = new WindowsUpdateAgentInfo(); var currentVersion = info.GetInfo("ApiMajorVersion").ToString().Trim() + "." + info.GetInfo("ApiMinorVersion").ToString().Trim() + " (" + info.GetInfo("ProductVersionString").ToString().Trim() + ")"; AppLog.Line(Program.fmt("Windows Update Agent Version: {0}", currentVersion)); }
private static IInstallationResult installUpdates(UpdateSession session, UpdateCollection toInstallAutomatically) { Console.WriteLine("Downloading {0} updates", toInstallAutomatically.Count); UpdateDownloader downloader = session.CreateUpdateDownloader(); downloader.Updates = toInstallAutomatically; downloader.Download(); UpdateCollection updatesToInstall = new UpdateCollection(); foreach (IUpdate update in toInstallAutomatically) { if (update.IsDownloaded) { updatesToInstall.Add(update); } } Console.WriteLine("Installing {0} updates", updatesToInstall.Count); IUpdateInstaller installer = session.CreateUpdateInstaller(); // don't let the updater prompt for CDs/DVDs. installer.AllowSourcePrompts = false; IUpdateInstaller2 quietinstall; quietinstall = (IUpdateInstaller2)session.CreateUpdateInstaller(); quietinstall.Updates = updatesToInstall; quietinstall.ForceQuiet = true; IInstallationResult installtionRes = quietinstall.Install(); Console.WriteLine("Updates complete!"); return installtionRes; }
/// <summary> /// Clean up the resources. /// </summary> public void Dispose() { this._settingsManager = null; this._wuCollectionWrapper = null; this._uSession = null; _eventSource.Message("Windows Update Manager disposed."); }
/* * Call WUApi to get available updates. Returns two int's * <Important Updates,Recommended Updates> */ static public Tuple <int, int> GetServerUpdates(string serverName) { UpdateCollection uc = null; int cntImpUpdate = 0; int cntRecUpdate = 0; try { //Create WUApi session and filter results to only include Software //and exclude installed and hidden updates. Type t = Type.GetTypeFromProgID("Microsoft.Update.Session", serverName); UpdateSession session = (UpdateSession)Activator.CreateInstance(t); session.ClientApplicationID = "BR Server Update"; IUpdateSearcher updateSearcher = session.CreateUpdateSearcher(); ISearchResult iSResult = updateSearcher.Search("Type = 'Software' and IsHidden = 0 and IsInstalled = 0"); uc = iSResult.Updates; //loop through updates and identify update priority. foreach (IUpdate u in uc) { string cat = u.Categories[0].Name; if (cat != "Tools" && cat != "Feature Packs" && cat != "Updates") { cntImpUpdate++; } else { cntRecUpdate++; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(Tuple.Create(cntImpUpdate, cntRecUpdate)); }
static void Main(string[] args) { UpdateSession updateSession = new UpdateSession(); Console.WriteLine("1/3 searching"); IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); ISearchResult searchResult = updateSearcher.Search("Type='Driver' And IsInstalled=0 And IsHidden=0"); foreach (IUpdate update in searchResult.Updates) { Console.WriteLine(update.Title); } Console.WriteLine("2/3 downloading"); IUpdateDownloader updateDownloader = updateSession.CreateUpdateDownloader(); updateDownloader.Updates = searchResult.Updates; updateDownloader.Download(); Console.WriteLine("3/3 installing"); IUpdateInstaller updateInstaller = updateSession.CreateUpdateInstaller(); updateInstaller.Updates = searchResult.Updates; updateInstaller.Install(); }
public void StartSearchForUpdates(string[] kbIdsToInstall, string[] kbIdsToIgnore) { var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext(); Task.Factory.StartNew(() => { try { var session = new UpdateSession(); var searcher = session.CreateUpdateSearcher(); searcher.Online = true; var result = searcher.Search("IsInstalled=0 AND IsHidden=0"); var installedUpdates = 0; if (kbIdsToInstall.Length > 0) { var updatesToInstall = _GetUpdatesToInstall(kbIdsToInstall, result.Updates); installedUpdates = _InstallUpdates(session, updatesToInstall); } var updatesToIgnore = 0; if (kbIdsToIgnore.Length > 0) { updatesToIgnore = _GetUpdatesToIgnore(result.Updates, kbIdsToIgnore); } return(new UpdateResult(result.Updates.Count - installedUpdates - updatesToIgnore, installedUpdates)); } catch (Exception) { return(new UpdateResult()); } }) .ContinueWith(task => mOnSearchFinished(task.Result), scheduler); }
public static List <string> listUpdateHistory() { //WUApi List <string> result = new List <string>(200); try { UpdateSession uSession = new UpdateSession(); IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher(); uSearcher.Online = false; ISearchResult sResult = uSearcher.Search("IsInstalled=1 And IsHidden=0"); string sw = "Количество обновлений через WUApi: " + sResult.Updates.Count; result.Add(sw); foreach (IUpdate update in sResult.Updates) { result.Add(update.Title); } } catch (Exception ex) { result.Add("Что-то пошло не так: " + ex.Message); } return(result); }
public static void UpdatesAvailable(int y) { UpdateSession updateSession = new UpdateSession(); IUpdateSearcher updateSearchResult = updateSession.CreateUpdateSearcher(); updateSearchResult.Online = true; //checks for updates online ISearchResult searchResults = updateSearchResult.Search("IsInstalled=0 AND IsPresent=0"); //for the above search criteria refer to //http://msdn.microsoft.com/en-us/library/windows/desktop/aa386526(v=VS.85).aspx //Check the remarks section if (y == 0) { Console.WriteLine("Number of updates available: " + searchResults.Updates.Count); } if (y == 1) { if (File.Exists("available.txt")) { File.Delete("available.txt"); } string summary = "Available update count: " + searchResults.Updates.Count; File.AppendAllText("available.txt", summary + Environment.NewLine); foreach (IUpdate z in searchResults.Updates) { string content = z.Title; File.AppendAllText("available.txt", content + Environment.NewLine); } Console.WriteLine("Available Update details written to available.txt"); } }
private UpdateCollection GetPendingUpdates() { UpdateCollection pendingUpdates = new UpdateCollection(); try { Type t = Type.GetTypeFromProgID("Microsoft.Update.Session", computerName); UpdateSession uSession = (UpdateSession)Activator.CreateInstance(t); IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher(); uSearcher.ServerSelection = ServerSelection.ssManagedServer; uSearcher.IncludePotentiallySupersededUpdates = false; uSearcher.Online = false; ISearchResult sResult = uSearcher.Search("IsInstalled=0 And IsHidden=0 And Type='Software'"); if (sResult.ResultCode == OperationResultCode.orcSucceeded && sResult.Updates.Count != 0) { pendingUpdates = sResult.Updates; } } catch (UnauthorizedAccessException) { System.Windows.Forms.MessageBox.Show("Unauthorized Access Exception ! Ensure you have admin privileges on the remote computer."); } catch (System.Runtime.InteropServices.COMException) { System.Windows.Forms.MessageBox.Show("COM Exception ! Verify the firewall settings on the remote computer."); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.GetType().ToString() + "\r\n" + ex.Message); } return(pendingUpdates); }
public async Task SearchAsyncCancelTest(string criteria) { var Token = CancellationTokenSource.CreateLinkedTokenSource(TokenSource.Token, new CancellationTokenSource(TimeSpan.FromSeconds(5)).Token).Token; var exception = await Assert.ThrowsExceptionAsync <TaskCanceledException>(async() => { try { var Session = new UpdateSession(); var Searcher = Session.CreateUpdateSearcher(); var Result = string.IsNullOrEmpty(criteria) ? await Searcher.SearchAsync(Token) : await Searcher.SearchAsync(criteria, Token); } catch (COMException e) { var state = e.GetWindowsUpdateHResult(); if (Enum.IsDefined(state.GetType(), state)) { Assert.Fail($"ERROR: {state}(0x{(uint)state:x}) {state.GetDescription()}"); } throw; } }); Assert.AreEqual(exception.CancellationToken, Token); }
public void InstallPatches(bool rebootIfNeeded, bool onlyList, Stream output) { Bender.WriteLine("Searching for updates...", output); UpdateSession session = new UpdateSession(); List <IUpdate5> updates = GetPatches(session, output); PrintStats(updates, output); if (onlyList) { ListPatches(updates, output); } else { DownloadPatches(session, updates, output); updates = GetPatches(session, output); InstallPatches(session, updates, rebootIfNeeded, output); } return; }
public static void Initialize(IServiceProvider serviceProvider) { using (var context = new UpdateHistoryContext( serviceProvider.GetRequiredService < DbContextOptions <UpdateHistoryContext> >())) { if (!context.Server.Any()) { return; // DB has been seeded } foreach (Server item in context.Server) { try { Type t = Type.GetTypeFromProgID("Microsoft.Update.Session", item.Location); //wcswapp01.intellig.local OH0KLT733D7S2.global.ds.honeywell.com labengdemctl00.labmasoh.local wcbuildapp02.intellig.local UpdateSession session = (UpdateSession)Activator.CreateInstance(t); item.NoAccess = false; } catch { item.NoAccess = true; } } context.SaveChanges(); } }
public bool FindUpdates(string patch) { //var session = new UpdateSession(); //var searcher = session.CreateUpdateSearcher(); //searcher.ServerSelection = ServerSelection.ssWindowsUpdate; //ISearchResult searchresult = searcher.Search(""); //UpdateCollection updatecollection = searchresult.Updates; //Console.WriteLine("Found " + updatecollection.Count + " updates."); //foreach (IUpdate5 update in updatecollection) //{ // Console.WriteLine(update.Title); //} var updateSession = new UpdateSession(); var updateSearcher = updateSession.CreateUpdateSearcher(); var count = updateSearcher.GetTotalHistoryCount(); if (count == 0) { return(false); } var history = updateSearcher.QueryHistory(0, count); for (int i = 0; i < count; i++) { Logme(Color.Gold, $"{history[i].Title}"); if (history[i].Title.Contains("KB" + patch)) { return(true); } } return(false); }
public async Task InstallAsync2() { if (!IsInRoleAdministrator()) { Assert.Inconclusive("user isn't in role administrator"); } try { var Session = new UpdateSession(); var Searcher = Session.CreateUpdateSearcher(); var SearchResult = await Searcher.SearchAsync("IsInstalled=0"); var InstallableUpdate = SearchResult.Updates.Cast <IUpdate>().Where(u => u.IsDownloaded).Take(1); var Installer = Session.CreateUpdateInstaller(); Installer.Updates = InstallableUpdate.AddBundle().ToUpdateCollection(); foreach (var Update in Installer.Updates.Cast <IUpdate>()) { Debug.WriteLine($"UPDATE {IUpdateToString(Update)}"); } Installer.IsForced = true; var InstallResult = await Installer.InstallAsync(TokenSource.Token); Debug.WriteLine($"RESULT: {IInstallationResultToString(InstallResult)}"); } catch (COMException e) { var state = e.GetWindowsUpdateHResult(); if (Enum.IsDefined(state.GetType(), state)) { Assert.Fail($"ERROR: {state}(0x{(uint)state:x}) {state.GetDescription()}"); } throw; } }
public static void InstallUpdates(UpdateCollection DownloadedUpdates) { Console.WriteLine("Installing updates now..."); var UpdateSession = new UpdateSession(); var InstallAgent = UpdateSession.CreateUpdateInstaller() as UpdateInstaller; InstallAgent.Updates = DownloadedUpdates; //Starts a synchronous installation of the updates. // http://msdn.microsoft.com/en-us/library/windows/desktop/aa386491(v=VS.85).aspx#methods if (DownloadedUpdates.Count > 0) { var InstallResult = InstallAgent.Install(); if (InstallResult.ResultCode == OperationResultCode.orcSucceeded) { Console.WriteLine("Updates installed succesfully"); if (InstallResult.RebootRequired == true) { Console.WriteLine("Reboot is required for one of more updates."); } } else { Console.WriteLine("Updates failed to install do it manually"); } } else { Console.WriteLine("The computer that this script was executed is up to date"); } }
internal static List<UpdateInfo> CheckUpdatesAvailable() { List<UpdateInfo> rslt = new List<UpdateInfo>(); try { UpdateSession uSess = new UpdateSession(); IUpdateSearcher uSearcher = uSess.CreateUpdateSearcher(); ISearchResult searchResult = uSearcher.Search("IsInstalled=0 and Type='Software'"); if (searchResult.Updates.Count > 0) { foreach (IUpdate x in searchResult.Updates) { if (x.IsHidden == true) continue; UpdateInfo ui = new UpdateInfo(); ui.Description = x.Title; foreach (ICategory cat in x.Categories) { switch(cat.Type) { case "UpdateClassification": ui.UpdateType = cat.Name; if (CheckingConstants.Critical == cat.Name) ui.Priority = 0; else if (CheckingConstants.Security == cat.Name) ui.Priority = 1; else if (CheckingConstants.Definition == cat.Name) ui.Priority = 2; else if (CheckingConstants.Updates == cat.Name) ui.Priority = 3; else if (CheckingConstants.Feature == cat.Name) ui.Priority = 4; else ui.Priority = 255; break; case "Product": ui.Product = cat.Name; break; case "ProductFamily" : ui.ProductFamily = cat.Name; break; case "Company": ui.Company = cat.Name; break; } } rslt.Add(ui); } } } catch (Exception ex) { throw new Exception("NscaWinUpdateModule: " + ex.Message); } return rslt; }
private IUpdateSearcher GetNewSearcher(bool online = false) { UpdateSession updateSession = new UpdateSession(); IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); updateSearcher.Online = online; return(updateSearcher); }
private void iUpdateDownload() { UpdateSession = new UpdateSession(); iUpdateDownloader = UpdateSession.CreateUpdateDownloader(); iUpdateDownloader.Updates = NewUpdatesCollection; iUpdateDownloader.Priority = DownloadPriority.dpHigh; iDownloadJob = iUpdateDownloader.BeginDownload(new iUpdateDownloader_onProgressChanged(this), new iUpdateDownloader_onCompleted(this), new iUpdateDownloader_state(this)); }
private void OnUpdateSession(UpdateSession msg) { if (sessions.TryGetValue(Sender, out TaskSession session)) { session.Height = msg.Height; session.Latency = msg.Latency; } }
private void iUpdateSearch() { UpdateSession = new UpdateSession(); iUpdateSearcher = UpdateSession.CreateUpdateSearcher(); // Only Check Online.. iUpdateSearcher.Online = true; // Begin Asynchronous IUpdateSearcher... iSearchJob = iUpdateSearcher.BeginSearch("IsInstalled=0 AND IsPresent=0", new iUpdateSearcher_onCompleted(this), new iUpdateSearcher_state(this)); }
private static ISearchResult CheckForUpdates(UpdateSession session) { ISearchResult uResult; Console.WriteLine("Checking for updates!"); session = new UpdateSession(); IUpdateSearcher uSearcher = session.CreateUpdateSearcher(); uResult = uSearcher.Search("IsInstalled = 0 and Type='Software'"); return uResult; }
static void Main(string[] args) { var session = new UpdateSession(); var searcher = session.CreateUpdateSearcher(); searcher.Online = false; var result = searcher.Search("IsInstalled=1"); Console.WriteLine($"Found {result.Updates.Count} installed updates"); Console.Read(); }
public List <Metric> GetMetrics() { var session = new UpdateSession(); ISearchResult uResult; var updateChecker = new AutomaticUpdatesClass(); var results = new List <Metric>(); results.Add(new Metric("windows.updates.enabled", updateChecker.ServiceEnabled ? 1 : 0)); if (!updateChecker.ServiceEnabled) { return(results); } int totalUpdates = 0; int criticalUpdates = 0; int updatesNeedingReboot = 0; uResult = CheckForUpdates(session); if (uResult != null) { foreach (IUpdate5 uResultUpdate in uResult.Updates) { if (uResultUpdate == null) { continue; } if (!String.IsNullOrWhiteSpace(uResultUpdate.MsrcSeverity) && uResultUpdate.MsrcSeverity.Contains("Critical")) { criticalUpdates++; } totalUpdates++; if (uResultUpdate.RebootRequired) { updatesNeedingReboot++; } } } results.Add(new Metric("windows.updates.count", totalUpdates, tags: new Dictionary <string, string> { { "severity", "all" } })); results.Add(new Metric("windows.updates.count", criticalUpdates, tags: new Dictionary <string, string> { { "severity", "critical" } })); results.Add(new Metric("windows.updates.rebootcount", updatesNeedingReboot, tags: new Dictionary <string, string> { { "severity", "all" } })); return(results); }
static bool InstallUpdates_WUApiLib() { UpdateSession updateSession = new UpdateSession(); // Activator.CreateInstance(updateSessionType); IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); Console.WriteLine("Searching for available updates..."); ISearchResult searchResult; try { searchResult = updateSearcher.Search(query); } catch (COMException e) { Console.WriteLine(WUError.GetHRMessage(e.HResult)); return false; } UpdateCollection updatesToInstall = new UpdateCollection(); for (int i = 0; i < searchResult.Updates.Count; ++i) { IUpdate update = searchResult.Updates[i]; Console.WriteLine(update.Title); updatesToInstall.Add(update); } if (searchResult.Updates.Count == 0) { Console.WriteLine("No updates found."); return false; } if (listUpdates) { return false; } if (updatesToInstall.Count > 0) { IUpdateInstaller installer = updateSession.CreateUpdateInstaller(); installer.Updates = updatesToInstall; IInstallationResult installResult; try { installResult = installer.Install(); } catch (COMException e) { Console.WriteLine(WUError.GetHRMessage(e.HResult)); return false; } Console.WriteLine("Installation result code: " + installResult.ResultCode); Console.WriteLine("Reboot required: " + installResult.RebootRequired); return installResult.RebootRequired; } return false; }
public static IInstallationResult InstallUpdates(UpdateCollection DownloadedUpdates, string query) { var UpdateSession = new UpdateSession(); var InstallAgent = UpdateSession.CreateUpdateInstaller() as UpdateInstaller; InstallAgent.Updates = DownloadedUpdates; //Starts a synchronous installation of the updates. // http://msdn.microsoft.com/en-us/library/windows/desktop/aa386491(v=VS.85).aspx#methods return(InstallAgent.Install()); }
public List<OutputInterface> getResult() { var result = new List<OutputInterface>(); // http://www.nullskull.com/a/1592/install-windows-updates-using-c--wuapi.aspx UpdateSession uSession = new UpdateSession(); IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher(); ISearchResult uResult = uSearcher.Search("IsInstalled=0 and Type = 'Software'"); return result; }
/// <summary> /// lists updates that are hidden on the local machine /// </summary> /// <returns>Returns a list of hidden updates, if any.</returns> public static List<UpdateInfo> listHiddenUpdates() { UpdateSession session = new UpdateSession(); IUpdateSearcher updateSearcher = session.CreateUpdateSearcher(); //Do not go online to search for updates. We want to be fast(er). updateSearcher.Online = false; //Also include older, superseded updates. updateSearcher.IncludePotentiallySupersededUpdates = true; var searchResult = updateSearcher.Search("IsHidden=1"); int count = searchResult.Updates.Count; List<UpdateInfo> result = new List<UpdateInfo>(); for (int i = 0; i < count; ++i) { UpdateInfo info = new UpdateInfo(); info.ID = searchResult.Updates[i].Identity.UpdateID; info.title = searchResult.Updates[i].Title; info.minDownloadSize = searchResult.Updates[i].MinDownloadSize; info.maxDownloadSize = searchResult.Updates[i].MaxDownloadSize; info.uninstallable = searchResult.Updates[i].IsUninstallable; info.securityBulletins.Clear(); if (searchResult.Updates[i].SecurityBulletinIDs != null) { foreach (var item in searchResult.Updates[i].SecurityBulletinIDs) { info.securityBulletins.Add(item.ToString()); } //foreach } //if info.KBArticleIDs.Clear(); if (null != searchResult.Updates[i].KBArticleIDs) { foreach (var item in searchResult.Updates[i].KBArticleIDs) { info.KBArticleIDs.Add(item.ToString()); } //foreach } //if result.Add(info); } //for searchResult = null; updateSearcher = null; session = null; return result; }
private void Edit_Expense(object sender, MouseButtonEventArgs e) { try { DataGrid dg = sender as DataGrid; SessionsGrid p = (SessionsGrid)dg.SelectedItems[0]; // OR: Patient p = (Patient)dg.SelectedItem; UpdateSession up = new UpdateSession(p); up.ShowDialog(); } catch (Exception error) { } // Refresh the grid Refresh_SessionGrid(); }
private void DownloadPatches(UpdateSession session, List<IUpdate5> updates) { Log("Downloading " + updates.Count + " patches..."); foreach (IUpdate5 update in updates.OrderBy(u => u.Title)) { if (update.IsDownloaded) { Log("Patch is already downloaded: " + update.Title); continue; } UpdateCollection updateCollection = new UpdateCollection(); updateCollection.Add(update); UpdateDownloader downloader = session.CreateUpdateDownloader(); downloader.Updates = updateCollection; bool downloaded = false; for (int tries = 0; tries < 3 && !downloaded; tries++) { try { string printtry = tries > 0 ? " (try " + (tries + 1) + ")" : string.Empty; Log("Downloading" + printtry + ": " + update.Title + ": " + GetPrintSize(update.MaxDownloadSize) + " MB."); IDownloadResult downloadresult = downloader.Download(); if (downloadresult.ResultCode == OperationResultCode.orcSucceeded) { downloaded = true; } else { Log("Couldn't download patch: " + downloadresult.ResultCode + ": 0x" + downloadresult.HResult.ToString("X")); } } catch (COMException ex) { Log("Couldn't download patch: 0x" + ex.HResult.ToString("X")); } } } }
internal static bool CheckNetworkFixInstalled() { bool ret = false; var updateSession = new UpdateSession(); var updateSearcher = updateSession.CreateUpdateSearcher(); var count = updateSearcher.GetTotalHistoryCount(); if (count > 0) { var history = updateSearcher.QueryHistory(0, count); for (int i = 0; i < count; ++i) { if(history[i].Title.Contains("KB2580188")) { ret = true; break; } } } return (ret); }
private static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => { ExceptionHandler((Exception) eventArgs.ExceptionObject); }; if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major == 10) { Console.WriteLine("Wait a second, you are RUNNING windows 10! You shouldn't be running this!"); return; } try { Console.WriteLine("Creating Windows Update Session..."); // Because who needs a .Create() method for a COM interop object. Right Microsoft? Type t = Type.GetTypeFromProgID("Microsoft.Update.Session"); _session = (UpdateSession) Activator.CreateInstance(t); Console.WriteLine("Creating Search Object..."); _updateSearcher = _session.CreateUpdateSearcher(); Console.WriteLine("Starting search for all updates (This might take a while)..."); // Not joking, takes forever. _callback = new AsyncUpdate(); _updateSearcher.BeginSearch("(IsInstalled=1) OR (IsInstalled=0 AND IsHidden=0)", _callback, null); while (!_done) Thread.Sleep(100); } catch (Exception exception) { ExceptionHandler(exception); } }
/// <summary> /// lists the update history /// </summary> /// <returns>returns the applied updates as list of UpdateOpInfo structures</returns> public static List<UpdateOpInfo> listUpdateHistory() { UpdateSession session = new UpdateSession(); IUpdateSearcher updateSearcher = session.CreateUpdateSearcher(); int count = updateSearcher.GetTotalHistoryCount(); var history = updateSearcher.QueryHistory(0, count); List<UpdateOpInfo> result = new List<UpdateOpInfo>(); for (int i = 0; i < count; ++i) { UpdateOpInfo opInfo = new UpdateOpInfo(); /* Note: The Date value seems to be in UTC and not in local * time, because this value was off by a few hours. */ opInfo.date = history[i].Date; opInfo.ID = history[i].UpdateIdentity.UpdateID; opInfo.operation = history[i].Operation; opInfo.result = history[i].ResultCode; opInfo.title = history[i].Title; result.Add(opInfo); } //for history = null; updateSearcher = null; session = null; return result; }
private List<IUpdate5> GetPatches(UpdateSession session) { UpdateServiceManager manager = new UpdateServiceManager(); Log("Found " + manager.Services.Count + " update services."); List<IUpdate5> updates = new List<IUpdate5>(); foreach (IUpdateService2 service in manager.Services) { Log("Retrieving patches from: " + service.Name); try { var searcher = session.CreateUpdateSearcher(); searcher.ServerSelection = ServerSelection.ssWindowsUpdate; searcher.ServiceID = service.ServiceID; ISearchResult searchresult = searcher.Search(""); UpdateCollection updatecollection = searchresult.Updates; Log("Found " + updatecollection.Count + " updates."); foreach (IUpdate5 update in updatecollection) { if (!updates.Any(u => u.Title == update.Title)) { updates.Add(update); } } } catch (COMException ex) { Log("Couldn't retrive patches: 0x" + ex.HResult.ToString("X")); Log(ex.ToString()); } } return updates; }
public static WindowsUpdateResult InstallUpdates(JobClientInterface jci) { UpdateSession updateSession = new UpdateSession(); IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); UpdateCollection updatesToDownload = new UpdateCollection(); jci.LogString("Searching For Updates..."); ISearchResult sr = updateSearcher.Search("IsInstalled=0 and Type='Software' and AutoSelectOnWebSites=1"); if (sr.Updates.Count == 0) { jci.LogString("No New Updates Found"); return new WindowsUpdateResult(false, false); } for (int i = 0; i < sr.Updates.Count; i++) { IUpdate update = sr.Updates[i]; if (!update.IsDownloaded) { if (update.InstallationBehavior.CanRequestUserInput) { jci.LogString("Ignoring update \"" + update.Title + "\" because it could require user input."); continue; } jci.LogString("Queuing Download of :" + update.Title); updatesToDownload.Add(update); } } if (updatesToDownload.Count > 0) { jci.LogString("Downloading Updates..."); UpdateDownloader downloader = updateSession.CreateUpdateDownloader(); downloader.Updates = updatesToDownload; downloader.Download(); } UpdateCollection updatesToInstall = new UpdateCollection(); for (int i = 0; i < sr.Updates.Count; i++) { IUpdate update = sr.Updates[i]; if (update.IsDownloaded) { if (!update.EulaAccepted) { update.AcceptEula(); } if (update.InstallationBehavior.CanRequestUserInput) { jci.LogString("Ignoring update \"" + update.Title + "\" because it could require user input."); continue; } jci.LogString("Queuing Install of :" + update.Title); updatesToInstall.Add(update); } } if (updatesToInstall.Count > 0) { jci.LogString("Installing Updates..."); IUpdateInstaller installer = updateSession.CreateUpdateInstaller(); installer.Updates = updatesToInstall; IInstallationResult installationResult = installer.Install(); jci.LogString("Installation Finished"); jci.LogString("Update Result Code: " + installationResult.ResultCode.ToString()); bool rebootRequired = installationResult.RebootRequired; if (rebootRequired) { jci.LogString("Reboot Required"); } return new WindowsUpdateResult(true, rebootRequired); } else { jci.LogString("No New Updates Found"); return new WindowsUpdateResult(false, false); } }
/// <summary> /// tries to uninstall the given updates /// </summary> /// <param name="theUpdates">collection of updates, must not be empty</param> /// <param name="needsReboot">Reference parameter that will be set to /// true, if a reboot is required after the operation. Will be set to /// false, if no reboot is required. Value is undefined, if the function /// fails, i.e. returns false.</param> /// <returns></returns> public static bool uninstallUpdates(UpdateCollection theUpdates, ref bool needsReboot) { //No empty stuff! if (null == theUpdates) return false; if (theUpdates.Count <= 0) return false; UpdateSession session = new UpdateSession(); IUpdateInstaller updInstaller = session.CreateUpdateInstaller(); updInstaller.Updates = theUpdates; IInstallationResult res = updInstaller.Uninstall(); needsReboot = res.RebootRequired; bool success = (res.ResultCode == OperationResultCode.orcSucceeded || res.ResultCode == OperationResultCode.orcSucceededWithErrors); res = null; updInstaller = null; session = null; return success; }
void BeginSearchUpdate() { _updateSession = new UpdateSession(); _updateSearcher = _updateSession.CreateUpdateSearcher(); // Only Check Online.. _updateSearcher.Online = true; this.AppendString("正在搜索更新,请耐心等候 ...\r\n(如果您这台电脑是安装 Windows 操作系统后第一次更新,可能会在这一步耗费较长时间,请一定耐心等待)\r\n"); // Begin Asynchronous IUpdateSearcher... _searchJob = _updateSearcher.BeginSearch("IsInstalled=0 AND IsPresent=0", new SearchCompleteFunc(this), null // new UpdateSearcher_state(this) ); }
public static Operations.SavedOpData InstallWindowsUpdate(Operations.SavedOpData update) { try { IUpdateSession session = new UpdateSession(); var updatesToInstall = LoadUpdateCache(update, _allAvailableUpdatesList); var installer = (IUpdateInstaller2)session.CreateUpdateInstaller(); //Check that there were no errors when processing LoadUpdateCache() if (updatesToInstall == null) { update.error = update.filedata_app_name + " failed to install, Internal Windows Update API Error occured when attempting to install this Update. Please refer to agent logs for details."; update.success = false.ToString().ToLower(); return update; } //Make sure we have some updates to install if (updatesToInstall.Count <= 0) { update.success = false.ToString().ToLower(); update.error = "There are no available updates to install, its possible that this update was manually installed and as a result, is not longer available."; Logger.Log("The update was not available for install: {0}", LogLevel.Info, update.filedata_app_name + ", Debug: updatesToInstall is empty."); return update; } //Check if the update is already installed and remove it from the list of updates to install. for (int x = 0; x < updatesToInstall.Count; x++) { if (updatesToInstall[x].IsInstalled) updatesToInstall.RemoveAt(x); } //Final preparation for the installer, assigning the list of updates with all bundles in place to the Updates property. installer.ForceQuiet = true; installer.AllowSourcePrompts = false; installer.Updates = updatesToInstall; //Verify if we require a reboot before installing any updates. if (installer.RebootRequiredBeforeInstallation) { update.success = false.ToString().ToLower(); update.error = "A System Reboot is required before attempting a Windows Update installation."; update.reboot_required = true.ToString().ToLower(); Logger.Log("A System Reboot is required before attempting a Windows Update installation, sending back results."); return update; } //Iterate each update to accept the EULA (Mandatory) foreach (IUpdate updateNode in installer.Updates) { updateNode.AcceptEula(); } //Perform the installation and retrieve the results for the update. var installationRes = installer.Install(); var installResult = installationRes.GetUpdateResult(0); if (installResult.ResultCode == OperationResultCode.orcSucceeded) { update.success = true.ToString().ToLower(); update.reboot_required = installResult.RebootRequired.ToString(); Logger.Log("Update Installed Successfully: {0}", LogLevel.Info, update.filedata_app_name); return update; } return ErrorResult(update, installationRes, "Update failed" ); } catch (Exception e) { return ErrorResultsException(update, e); } }
private static UpdateCollection RetrieveUpdatesAvailable() { var updateCollection = new UpdateCollection(); IUpdateSession session = new UpdateSession(); var wsusEnabled = WSUS.IsWSUSEnabled(); try { var proxyUri = Settings.GetProxyFullAddressString(); if (proxyUri != null) session.WebProxy.Address = proxyUri; var searcher = session.CreateUpdateSearcher(); searcher.Online = true; //Assign proper WUAPI Server (WSUS or WUS) searcher.ServerSelection = wsusEnabled ? ServerSelection.ssManagedServer : ServerSelection.ssWindowsUpdate; ISearchResult searchResults = searcher.Search("IsInstalled=0 AND Type='Software' AND DeploymentAction='Installation'"); if (searchResults == null) { searcher.Online = false; Logger.Log("Unable to retrieve available updates via the Web, attempting local search."); searchResults = searcher.Search("IsInstalled=0 AND Type='Software' AND DeploymentAction='Installation'"); } if (searchResults.ResultCode == OperationResultCode.orcSucceeded) { updateCollection = searchResults.Updates; foreach (IUpdate update in searchResults.Updates) { AllAvailableUpdatesParsed.Add(ConvertToApplication(update, null, wsusEnabled)); } } } catch (Exception e) { Logger.Log("Could not retrieve collection of updates.", LogLevel.Error); Logger.LogException(e); updateCollection = null; } return updateCollection; }
protected override void ProcessRecord() { base.ProcessRecord(); UpdateSession updateSession = new UpdateSession(); IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); if (FromMicrosoft) { int ssWindowsUpdate = 2; updateSearcher.ServerSelection = (ServerSelection)ssWindowsUpdate; } searchResult = updateSearcher.Search(Criteria); }
public static List<Application> GetInstalledUpdates() { IUpdateSession session = new UpdateSession(); Logger.Log("Retrieving list of Installed Windows Updates."); var installedUpdates = new List<Application>(); var wsusEnabled = WSUS.IsWSUSEnabled(); try { var searcher = session.CreateUpdateSearcher(); searcher.Online = false; //Assign proper WUAPI Server (WSUS or WUS) searcher.ServerSelection = wsusEnabled ? ServerSelection.ssManagedServer : ServerSelection.ssWindowsUpdate; ISearchResult searchResults = searcher.Search("IsInstalled = 1"); _allInstalledUpdatesList = searchResults.Updates; var count = searcher.GetTotalHistoryCount(); var history = count > 0 ? searcher.QueryHistory(0, count) : null; foreach (IUpdate update in _allInstalledUpdatesList) { var parsedUpdate = ConvertToApplication(update, history, wsusEnabled); installedUpdates.Add(parsedUpdate); } } catch (Exception e) { Logger.Log("Failed to find installed updates.", LogLevel.Error); Logger.LogException(e); } Logger.Log("Done."); return installedUpdates; }
private void InstallPatches(UpdateSession session, List<IUpdate5> updates) { Log("Installing " + updates.Count + " patches..."); bool reboot = false; foreach (IUpdate5 update in updates.OrderBy(u => u.Title)) { if (update.IsInstalled) { Log("Patch is already installed: " + update.Title); continue; } else if (!update.IsDownloaded) { Log("Patch isn't downloaded yet: " + update.Title); } else { try { Log("Installing: " + update.Title); UpdateCollection updateCollection = new UpdateCollection(); updateCollection.Add(update); IUpdateInstaller installer = session.CreateUpdateInstaller(); installer.Updates = updateCollection; IInstallationResult installresult = installer.Install(); if (installresult.ResultCode == OperationResultCode.orcSucceeded) { if (installresult.RebootRequired) { reboot = true; } } else { Log("Couldn't install patch: " + installresult.ResultCode + ": 0x" + installresult.HResult.ToString("X")); } } catch (COMException ex) { Log("Couldn't download patch: 0x" + ex.HResult.ToString("X")); } } } string regpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired"; if (reboot || CheckIfLocalMachineKeyExists(regpath)) { Log("Rebooting"); IntPtr hToken; TOKEN_PRIVILEGES tkp; OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out hToken); tkp.PrivilegeCount = 1; tkp.Privileges.Attributes = SE_PRIVILEGE_ENABLED; LookupPrivilegeValue("", SE_SHUTDOWN_NAME, out tkp.Privileges.pLuid); AdjustTokenPrivileges(hToken, false, ref tkp, 0U, IntPtr.Zero, IntPtr.Zero); if (!ExitWindowsEx(6, 0)) { Log("Couldn't reboot."); } } }
public static UpdateItem ProcessCheck(string branch, string flightLevel, Guid updateId) { UpdateSession uSession; IUpdateSearcher uSearcher; List<IUpdate> uCollection, uInCollection; ISearchResult sResult, ssResult; string updTitle = ""; Debug.PrintMessage(string.Format("Current Branch: {0}", branch)); Debug.PrintMessage(string.Format("Current Flight Level = \"{0}\"", flightLevel)); if (branch != null) { FlightRegistry.Branch = branch; Program.consoleWrite("Checking now: " + branch); } FlightRegistry.FlightLevel = flightLevel; uSession = new UpdateSession(); uSearcher = uSession.CreateUpdateSearcher(); if (Debug.IsDebug) { Console.WriteLine(""); Debug.PrintMessage("Created new IUpdateSession and IUpdateSearcher sessions."); } uSearcher.Online = true; uSearcher.ServiceID = _serviceGuid.ToString(); uSearcher.ServerSelection = ServerSelection.ssOthers; uSearcher.IncludePotentiallySupersededUpdates = true; uSearcher.ClientApplicationID = _userAgent; Debug.PrintMessage("IUpdateSearcher configuring is done."); StringBuilder ssSearch = new StringBuilder(); Debug.PrintMessage("Executing IUpdateSearcher::Search()..."); try { sResult = (updateId == Guid.Empty) ? uSearcher.Search(string.Join(" OR ", _categoryGuids.Select(s => string.Format("AppCategoryIDs contains '{0}' AND IsInstalled = 0 OR AppCategoryIDs contains '{0}' AND IsInstalled = 1", s)))) : uSearcher.Search(string.Format("IsInstalled = 0 And UpdateID = '{0}' And RevisionNumber = 2", updateId)); Debug.PrintMessage(string.Format("IUpdateSearcher::Search() done, returned {0} updates count.", sResult.Updates.Count)); } catch (Exception seException) { Console.WriteLine("An error occured while performing searching - {0}", seException.Message); Debug.PrintMessage("ERROR: Exception in IUpdateSearcher::Search(). " + string.Format("HResult = {0}, ", seException.HResult.ToString("X")) + string.Format("Message = '{0}'", seException.Message)); return null; } uCollection = new List<IUpdate>(); foreach (IUpdate update in sResult.Updates) { //Filters results which are related to given branch only. Space was added incase some results //contained same beginning (e.g. fbl_hyp and fbl_hyp_dev). if (update != null & update.Title.ToLower().Contains(FlightRegistry.Branch.ToLower() + " ")) uCollection.Add(update); } if (uCollection.Count == 0) { Console.WriteLine("No updates were found using given criteria(s)."); return null; } Console.WriteLine("Found {0} update(s).", uCollection.Count); // Sorting results //Array.Sort(uCollection, delegate (IUpdate up1, IUpdate up2) { return up1.Title.CompareTo(up2.Title); }); uCollection.Sort(delegate (IUpdate up1, IUpdate up2) { return up1.Title.CompareTo(up2.Title); }); Debug.PrintMessage("Results from IUpdateSearcher were saved in ISearchResult and were sorted."); UpdateCollection updCollection = new UpdateCollection(); foreach (IUpdate update in uCollection) { updCollection.Add(update); Console.WriteLine(" {0,-48} {1,-35} {2:#,###,###,###} bytes", update.Title, update.Identity.UpdateID, update.MaxDownloadSize); update.AcceptEula(); if (!Program.CheckAllBundledUpdates) continue; //Save array and sort if (update.SupersededUpdateIDs.Count != 0) { Debug.PrintMessage(string.Format("List of bundled updates ({0}):", update.SupersededUpdateIDs.Count)); foreach (string dbgSsUID in update.SupersededUpdateIDs) { Debug.PrintMessage(string.Format(" {0}", dbgSsUID)); } foreach (string ssUID in update.SupersededUpdateIDs) ssSearch.Append(string.Join(" Or ", _categoryGuids.Select(s => string.Format("(AppCategoryIds contains '{0}' and UpdateID = '{1}')", s, ssUID)))); ssSearch = ssSearch.Remove(ssSearch.Length - 3, 3); ssResult = uSearcher.Search(ssSearch.ToString()); Console.WriteLine(" Distinguished bundled updates count: {0}/{1}", ssResult.Updates.Count, update.SupersededUpdateIDs.Count); if (ssResult.Updates.Count != 0) { uInCollection = new List<IUpdate>(); foreach (IUpdate sUpdate in ssResult.Updates) { uInCollection.Add(sUpdate); } if (ssResult.Updates.Count != 1) uInCollection.Sort(delegate (IUpdate up1, IUpdate up2) { return up1.Title.CompareTo(up2.Title); }); foreach (IUpdate sUpdate in uInCollection) { if (sUpdate.Title.Length <= 23) updTitle = sUpdate.Title + "\t\t\t\t"; if (sUpdate.Title.Length > 23 && sUpdate.Title.Length <= 31) updTitle = sUpdate.Title + "\t\t\t"; if (sUpdate.Title.Length > 33 && sUpdate.Title.Length <= 40) updTitle = sUpdate.Title + "\t\t"; if (sUpdate.Title.Length > 40) updTitle = sUpdate.Title + "\t"; Console.WriteLine(" {0}\t{1}\t{2}", sUpdate.Identity.UpdateID, updTitle, sUpdate.MaxDownloadSize.ToString("0,000,000,000 bytes")); } } } else Console.WriteLine(" Distinguished bundled updates count: 0"); Console.WriteLine(""); ssSearch = new StringBuilder(); } Console.WriteLine(""); //Used to get only single result than showing other architecture/SKUs of a single build in results. UpdateItem updateObj = new UpdateItem(); updateObj.updateID = uCollection.ElementAt(uCollection.Count - 1).Identity.UpdateID; updateObj.updateTitle = uCollection.ElementAt(uCollection.Count - 1).Title; updateObj.updateSize = uCollection.ElementAt(uCollection.Count - 1).MaxDownloadSize; return updateObj; }
static void Main(string[] args) { bool addthisupdate, rebootMayBeRequired; UpdateSession uSession = new UpdateSession(); IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher(); uSession.ClientApplicationID = "ABS WUA"; uSearcher.Online = true; try { //processamento de updates - Scan ISearchResult sResult = uSearcher.Search("(IsInstalled=0 and Type='Software' and CategoryIDs contains '0FA1201D-4330-4FA8-8AE9-B877473B6441') or (IsInstalled=0 and Type='Software' and CategoryIDs contains 'E6CF1350-C01B-414D-A61F-263D14D133B4')"); Console.Write(sResult.Updates.Count + Environment.NewLine); foreach (IUpdate update in sResult.Updates) { Console.WriteLine(update.Title); } UpdateCollection updatesToDownload = new UpdateCollection(); foreach (IUpdate update in sResult.Updates) { addthisupdate = false; if (update.InstallationBehavior.CanRequestUserInput == true) { Console.WriteLine("skipping interactive update: " + update.Title); } else { if (update.EulaAccepted == false) { update.AcceptEula(); addthisupdate = true; } else { addthisupdate = true; } } if (addthisupdate == true) { updatesToDownload.Add(update); } } if (updatesToDownload.Count == 0) { Console.Write("All applicable updates were skipped."); } else { //processamento de updates - Download UpdateDownloader downloader = uSession.CreateUpdateDownloader(); downloader.Updates = updatesToDownload; downloader.Download(); //processamento de updates - Install UpdateCollection updatesToInstall = new UpdateCollection(); //UpdateInstaller updatesToInstall = uSession.CreateUpdateInstaller(); rebootMayBeRequired = false; foreach (IUpdate update in sResult.Updates) { if (update.IsDownloaded==true) { updatesToInstall.Add(update); if (update.InstallationBehavior.RebootBehavior > 0) { rebootMayBeRequired = true; } } } if (updatesToInstall.Count == 0) Console.Write("No updates were successfully downloaded."); if (rebootMayBeRequired == true) Console.Write("Reboot will be required."); //UpdateInstaller installer = uSession.CreateUpdateInstaller(); IUpdateInstaller installer = uSession.CreateUpdateInstaller(); installer.Updates = updatesToInstall; installer.Install(); } } catch (Exception ex) { Console.WriteLine("Something went wrong: " + ex.Message); } }
/// <summary> /// uninstall and hide the updates that match the given KB numbers /// </summary> /// <param name="numbersKB">knowledge base (KB) article numbers</param> /// <returns>Returns true, if uinstallation was successful. /// Returns false, if uninstallation failed.</returns> public bool uninstallAndHide(HashSet<uint> numbersKB, dlgtChangeStatusBarMessage ChangeStatusBarMessage) { if (null == numbersKB) return false; if (numbersKB.Count <= 0) return false; if (m_Busy) return false; m_Busy = true; UpdateSession session = new UpdateSession(); IUpdateSearcher updateSearcher = session.CreateUpdateSearcher(); //Do not go online to search for updates. We want to be fast(er). updateSearcher.Online = false; UpdateSearchCompleteCallback callback = new UpdateSearchCompleteCallback(); ChangeStatusBarMessage("Searching through installed updates... (This may take several minutes.)"); var searchJob = updateSearcher.BeginSearch("IsInstalled=1 or IsInstalled=0", callback, null); while (!searchJob.IsCompleted) { //Process application events. System.Windows.Forms.Application.DoEvents(); System.Threading.Thread.Sleep(200); } //while var searchResult = updateSearcher.EndSearch(searchJob); int count = searchResult.Updates.Count; ChangeStatusBarMessage("Hiding/blocking telemetry updates..."); System.Windows.Forms.Application.DoEvents(); System.Threading.Thread.Sleep(200); List<IUpdate> toBeRemoved = new List<IUpdate>(); int i = 0; for (i = 0; i < count; ++i) { if (containsKB(searchResult.Updates[i].KBArticleIDs, numbersKB)) { /* Hide update from future installations. This way we avoid * that the update might get installed again by an * automatic update. */ try { /* Hide update. This may throw an exception, if the * user has hidden the update manually while the search * was in progress. */ searchResult.Updates[i].IsHidden = true; } catch (Exception) { /* Ignore exception, there's not much we can * (or need to) do about it anyway. */ } //try-catch // If update is installed, but can be uninstalled, add it to the list. if (searchResult.Updates[i].IsInstalled && searchResult.Updates[i].IsUninstallable) { toBeRemoved.Add(searchResult.Updates[i]); } //if installed } //if KB matches } //for try { searchJob.RequestAbort(); searchJob.CleanUp(); } catch (Exception) { // Do nothing. } searchJob = null; searchResult = null; updateSearcher = null; session = null; //Finish, if there is nothing more to do. if (toBeRemoved.Count <= 0) { m_Busy = false; return true; } ChangeStatusBarMessage("Removing " + toBeRemoved.Count.ToString() + " installed telemetry update(s)..."); System.Windows.Forms.Application.DoEvents(); System.Threading.Thread.Sleep(200); UpdateCollection collection = new UpdateCollection(); foreach (var item in toBeRemoved) { collection.Add(item); } bool reboot = false; bool success = Updates.uninstallUpdates(collection, ref reboot); m_Busy = false; ChangeStatusBarMessage("Removal of telemetry update(s) is finished."); return success; }
private static UpdateCollection RetrieveUpdatesInstalled() { IUpdateSession session = new UpdateSession(); var updateCollection = new UpdateCollection(); var wsusEnabled = WSUS.IsWSUSEnabled(); try { var proxyUri = Settings.GetProxyFullAddressString(); if (proxyUri != null) session.WebProxy.Address = proxyUri; var searcher = session.CreateUpdateSearcher(); searcher.Online = false; //Assign proper WUAPI Server (WSUS or WUS) searcher.ServerSelection = wsusEnabled ? ServerSelection.ssManagedServer : ServerSelection.ssWindowsUpdate; ISearchResult searchResults = searcher.Search("IsInstalled = 1"); if (searchResults.ResultCode == OperationResultCode.orcSucceeded) { updateCollection = searchResults.Updates; foreach (IUpdate update in searchResults.Updates) { var parsedUpdate = ConvertToApplication(update, null ,wsusEnabled); AllInstalledUpdatesParsed.Add(parsedUpdate); } } } catch (Exception e) { Logger.Log("Could not retrieve collection of installed updates.", LogLevel.Error); Logger.LogException(e); updateCollection = null; } return updateCollection; }
static void Main(string[] args) { UpdateSession session = new UpdateSession(); ISearchResult uResult; AutomaticUpdatesClass updateChecker = new AutomaticUpdatesClass(); Console.WriteLine("Service enabled?" + updateChecker.ServiceEnabled); int attempts = 5; while (!updateChecker.ServiceEnabled && attempts >= 0){ attempts--; updateChecker.EnableService(); Thread.Sleep(2000); } Boolean moreUpdates = true; while (moreUpdates) { uResult = CheckForUpdates(session); UpdateCollection toInstallAutomatically = getAutoUpdates(uResult); if (toInstallAutomatically.Count > 0) { IInstallationResult installationRes = installUpdates(session, toInstallAutomatically); if (installationRes.RebootRequired) { Console.WriteLine("Rebooting to finish installation!"); moreUpdates = false; System.Diagnostics.Process.Start("ShutDown", "/r"); } } else { moreUpdates = false; System.Console.WriteLine("Updates Complete! Press a key to continue."); System.Console.ReadKey(); } } }
public static List<Application> GetAvailableUpdates() { IUpdateSession session = new UpdateSession(); Logger.Log("Retrieving new os updates information..."); var availableUpdates = new List<Application>(); var wsusEnabled = WSUS.IsWSUSEnabled(); try { //Use Proxy if needed var proxyUri = Settings.GetProxyFullAddressString(); if (proxyUri != null) session.WebProxy.Address = proxyUri; var searcher = session.CreateUpdateSearcher(); searcher.Online = true; //Assign proper WUAPI Server (WSUS or WUS) searcher.ServerSelection = wsusEnabled ? ServerSelection.ssManagedServer : ServerSelection.ssWindowsUpdate; ISearchResult searchResults = searcher.Search("IsInstalled=0 AND Type='Software' AND DeploymentAction='Installation'"); if (searchResults == null) { searcher.Online = false; Logger.Log("Unable to retrieve available updates via the Web, attempting local search."); searchResults = searcher.Search("IsInstalled=0 AND Type='Software' AND DeploymentAction='Installation'"); } _allAvailableUpdatesList = searchResults.Updates; foreach (IUpdate update in searchResults.Updates) { availableUpdates.Add(ConvertToApplication(update, null, wsusEnabled)); Logger.Log(update.Title); } } catch (Exception e) { Logger.Log("Failed to find new updates, please check connectivity and/or Windows Update Agent version.", LogLevel.Error); Logger.LogException(e); } Logger.Log("Done."); return availableUpdates; }
/// <summary> /// lists the installed updates (still experimental) /// </summary> /// <returns>returns a list of installed updates</returns> public static List<UpdateOpInfo> listInstalledUpdatesFromHistory() { UpdateSession session = new UpdateSession(); IUpdateSearcher updateSearcher = session.CreateUpdateSearcher(); int count = updateSearcher.GetTotalHistoryCount(); IUpdateHistoryEntryCollection foundUpdates = updateSearcher.QueryHistory(0, count); HashSet<UpdateOpInfo> set = new HashSet<UpdateOpInfo>(); for (int i = 0; i < count; ++i) { var upd = foundUpdates[i]; UpdateOpInfo ud = new UpdateOpInfo(); ud.title = upd.Title; ud.ID = upd.UpdateIdentity.UpdateID; /* Note: The Date value seems to be in UTC and not in local * time, because this value was off by a few hours. */ ud.date = upd.Date; ud.operation = upd.Operation; ud.result = upd.ResultCode; //Check whether we have to add or remove the update. if (isInstallSuccess(upd)) set.Add(ud); else if (isUninstallSuccess(upd)) set.Remove(ud); upd = null; ud = null; } //for foundUpdates = null; updateSearcher = null; session = null; List<UpdateOpInfo> result = new List<UpdateOpInfo>(); foreach (var item in set) { result.Add(item); } set = null; return result; }
void BeginDownloadUpdate() { this.AppendString("开始下载更新 ...\r\n"); _updateSession = new UpdateSession(); _updateDownloader = _updateSession.CreateUpdateDownloader(); _updateDownloader.Updates = _updateCollection; _updateDownloader.Priority = DownloadPriority.dpHigh; _downloadJob = _updateDownloader.BeginDownload(new DownloadProgressChangedFunc(this), new DownloadCompleteFunc(this), null // new UpdateDownloader_state(this) ); }