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); }
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(); }
private ISearchResult SearchUpdatesUtil(CancellationToken cancellationToken) { try { IUpdateSearcher uSearcher = this._uSession.CreateUpdateSearcher(); SearchCompletedCallback searchCompletedCallback = new SearchCompletedCallback(); string searchQuery = this._serviceSettings.WUQuery; ISearchJob searchJob = uSearcher.BeginSearch(searchQuery, searchCompletedCallback, null); TimeSpan operationTimeOut = TimeSpan.FromMinutes(this._serviceSettings.WUOperationTimeOutInMinutes); if ( !this._helper.WaitOnTask(searchCompletedCallback.Task, (int)operationTimeOut.TotalMilliseconds, cancellationToken)) { _eventSource.Message("searchJob : Requested Abort"); searchJob.RequestAbort(); } ISearchResult uResult = uSearcher.EndSearch(searchJob); return(uResult); } catch (Exception e) { _eventSource.InfoMessage("Exception while searching for Windows-Updates: {0}", e); return(null); } }
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); } }
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)); }
public async void CheckForUpdates(bool online = true) { try { DebugLog("Checking for updates..."); updateSession = new UpdateSession(); updateSearcher = updateSession.CreateUpdateSearcher(); updateSearcher.Online = online; DebugLog("Update searcher params are: " + Dump(updateSearcher)); searchJob_ = updateSearcher.BeginSearch("IsInstalled=0 and IsHidden = 0 and BrowseOnly=0", this, null); } catch (Exception ex) { VMManagementTool.Log.Error("WinUpdatesManager.CheckForUpdates", ex.ToString()); await Task.Yield(); CheckCompleted?.Invoke(false); } }
/* * 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)); }
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); }
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 WindowsUpdateAgent() { this.mUpdateSearcher = this.mUpdateSession.CreateUpdateSearcher(); int totalHistoryCount = this.mUpdateSearcher.GetTotalHistoryCount(); if (totalHistoryCount > 0) { this.mUpdateHistoryCollection = this.mUpdateSearcher.QueryHistory(0, totalHistoryCount); Regex regex = new Regex(@"KB\d{5,5}"); foreach (IUpdateHistoryEntry entry in this.mUpdateHistoryCollection) { Match match = regex.Match(entry.Title); if (match.Success) { if (this.mInstalledUpdates.ContainsKey(match.Value)) { if (this.mInstalledUpdates[match.Value].RevisionNumber < Convert.ToInt32(entry.UpdateIdentity.RevisionNumber)) { this.mInstalledUpdates[match.Value] = new WindowsUpdate(match.Value, entry.Title, new Guid(entry.UpdateIdentity.UpdateID), Convert.ToInt32(entry.UpdateIdentity.RevisionNumber)); } } else { this.mInstalledUpdates.Add(match.Value, new WindowsUpdate(match.Value, entry.Title, new Guid(entry.UpdateIdentity.UpdateID), Convert.ToInt32(entry.UpdateIdentity.RevisionNumber))); } } } regex = null; this.mUpdateHistoryCollection = null; } this.mUpdateSearcher = null; this.mUpdateSession = null; }
static void GetWindowsUpdatesHistory(IUpdateSearcher uSearcher) { int count = uSearcher.GetTotalHistoryCount(); IUpdateHistoryEntryCollection collections = uSearcher.QueryHistory(0, count); UpdateIdsHistory = new List <Dictionary <string, string> >(); foreach (var item in collections) { try { IUpdateHistoryEntry2 historyEntry = (IUpdateHistoryEntry2)item; Dictionary <string, string> hu = new Dictionary <string, string>(); hu["Title"] = historyEntry.Title; hu["UpdateID"] = historyEntry.UpdateIdentity.UpdateID.ToString(); hu["RevisionNumber"] = historyEntry.UpdateIdentity.RevisionNumber.ToString(); //foreach (var item1 in hu) //Console.WriteLine(item1.Key + " : " + item1.Value); UpdateIdsHistory.Add(hu); } catch (Exception ex) { Console.WriteLine(ex); } //Console.WriteLine(); } }
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); }
/// <summary> /// Creates a <see cref="WuApiController"/> which uses the given Interfaces to search, download and install updates. /// </summary> /// <param name="session">Session to be used.</param> /// <param name="updateCollectionFactory">Factory to create <see cref="IUpdateCollection"/>s.</param> /// <param name="systemInfo">System informations about the OS enviroment.</param> public WuApiController(IUpdateSession session, UpdateCollectionFactory updateCollectionFactory, ISystemInfo systemInfo) { if (session == null) { throw new ArgumentNullException(nameof(session)); } if (updateCollectionFactory == null) { throw new ArgumentNullException(nameof(updateCollectionFactory)); } if (systemInfo == null) { throw new ArgumentNullException(nameof(systemInfo)); } UpdateSession = session; UpdateSession.ClientApplicationID = this.GetType().FullName; UpdateSearcher = session.CreateUpdateSearcher(); UpdateDownloader = session.CreateUpdateDownloader(); UpdateInstaller = session.CreateUpdateInstaller(); UpdateCollectionFactory = updateCollectionFactory; SystemInfo = systemInfo; StateTransitions = SetupStateTransitions(); EnterState((SystemInfo.IsRebootRequired()) ? (WuProcessState) new WuStateRebootRequired() : new WuStateReady()); Log.Info("Initial state: " + _currentState.GetType().Name); if (Log.IsDebugEnabled) { OnStateChanged += (s, e) => { Log.Debug($"Event {nameof(OnStateChanged)} fired: {e.ToString()}"); }; OnAsyncOperationCompleted += (s, e) => { Log.Debug($"Event {nameof(OnAsyncOperationCompleted)} fired: {e.ToString()}"); }; OnProgressChanged += (s, e) => { Log.Debug($"Event {nameof(OnProgressChanged)} fired: {e.ToString()}"); }; } }
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 IUpdateSearcher GetNewSearcher(bool online = false) { UpdateSession updateSession = new UpdateSession(); IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); updateSearcher.Online = online; return(updateSearcher); }
public void LookForUpdates() { // make sure the server is supposed to get updates if (File.Exists(@"c:\scripts\MSBUpdateManager\_no_updates.txt")) { return; } ShouldInstallUpdates = (Program.Dash.GetServerStatus() == "Ready For Updates"); uDownloadList = new UpdateCollection(); uInstallList = new UpdateCollection(); uSearcher = uSession.CreateUpdateSearcher(); List <String> updateList = new List <string>(); List <int> update_ids = new List <int>(); update_ids.Add(-1); Program.Dash.status("Looking For Available Updates..."); uSearcher.Online = true; uResult = uSearcher.Search("IsInstalled=0 and Type='Software'"); if (uResult.Updates.Count > 0) { Program.Dash.status("There are " + uResult.Updates.Count + " available updates"); updateList.Add("Available Updates..."); foreach (IUpdate update in uResult.Updates) { this.processUpdate(update, updateList, uDownloadList, uInstallList); update_ids.Add(Program.Dash.getUpdateId(update)); } Program.Dash.status("Cleaning up superseded updates."); Program.Dash.CleanupUpdates(update_ids); // download any missing updates this.downloadUpdates(uDownloadList); // install any queued updates this.installUpdates(uInstallList); // update the status of updates this.UpdateUpdates(uResult.Updates); Program.Events.WriteEntry(string.Join(System.Environment.NewLine, updateList), EventLogEntryType.Information); Console.WriteLine(string.Join(System.Environment.NewLine, updateList)); } Program.Dash.status("Cleaning up superseded updates."); Program.Dash.CleanupUpdates(update_ids); // update server info Program.Dash.UpdateServerInfo(); this.SetServerStatusNominal(); }
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)); }
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); }
public bool Init() { if (!LoadServices(true)) { return(false); } mUpdateSearcher = mUpdateSession.CreateUpdateSearcher(); UpdateHistory(); return(true); }
static void InstallUpdatesT() { try { if (EV.WaitOne(1000) == false) { return; } EV.Reset(); Status.Text = "Checking for updates"; UpdateSession UpdateSession = new UpdateSession(); UpdateSession.ClientApplicationID = "Fox SDC Update Controller"; IUpdateSearcher upd = UpdateSession.CreateUpdateSearcher(); ISearchResult res = upd.Search("IsInstalled=0 and Type='Software' and IsHidden=0"); for (int i = 0; i < res.Updates.Count; i++) { Status.Text = "Downloading " + res.Updates[i].Title + " (" + (i + 1).ToString() + " of " + res.Updates.Count.ToString() + ")"; UpdateDownloader downloader = UpdateSession.CreateUpdateDownloader(); downloader.Updates = new WUApiLib.UpdateCollection(); downloader.Updates.Add(res.Updates[i]); downloader.Download(); } for (int i = 0; i < res.Updates.Count; i++) { Status.Text = "Installing " + res.Updates[i].Title + " (" + (i + 1).ToString() + " of " + res.Updates.Count.ToString() + ")"; IUpdateInstaller installer = UpdateSession.CreateUpdateInstaller(); if (installer.IsBusy == true) { return; } installer.Updates = new WUApiLib.UpdateCollection(); installer.Updates.Add(res.Updates[i]); IInstallationResult ires = installer.Install(); } } catch (Exception ee) { FoxEventLog.WriteEventLog("Failed to install WU " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); return; } finally { Status.Text = "Idle"; EV.Set(); } return; }
public IUpdateCollection GetAvailableUpdates() { var uSession = new UpdateSessionClass(); IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher(); Logger.DebugFormat("Searcher server selection: " + uSearcher.ServerSelection); Logger.DebugFormat("Searcher service ID: " + uSearcher.ServiceID); uSearcher.Online = false; ISearchResult uResult = uSearcher.Search("IsInstalled=0 and Type='Software'"); return(uResult.Updates); }
public List <InstalledUpdate> GetInstalledUpdates() { IUpdateSearcher updateSearcher = GetNewSearcher(online: false); int count = updateSearcher.GetTotalHistoryCount(); IUpdateHistoryEntryCollection history = updateSearcher.QueryHistory(0, count); List <InstalledUpdate> installedUpdates = new List <InstalledUpdate>(); for (int i = 0; i < count; ++i) { installedUpdates.Add(new InstalledUpdate(Title: history[i].Title, InstalledDate: history[i].Date)); } return(installedUpdates); }
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 void installUpdates() { try { UpdateSession uSession = new UpdateSession(); IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher(); ISearchResult uResult = uSearcher.Search("IsInstalled=0 and Type ='Software'"); if (uResult.Updates.Count != 0) { UpdateDownloader downloader = uSession.CreateUpdateDownloader(); downloader.Updates = uResult.Updates; downloader.Download(); UpdateCollection updatesToInstall = new UpdateCollection(); foreach (IUpdate update in uResult.Updates) { if (update.IsDownloaded) { updatesToInstall.Add(update); } } IUpdateInstaller installer = uSession.CreateUpdateInstaller(); installer.Updates = updatesToInstall; IInstallationResult installationRes = installer.Install(); for (int i = 0; i < updatesToInstall.Count; i++) { if (installationRes.GetUpdateResult(i).HResult == 0) { Console.WriteLine("INSTALLED : " + updatesToInstall[i].Title); } else { Console.WriteLine("FAILED : " + updatesToInstall[i].Title); } } } else { Console.WriteLine("THERE IS NOTHING TO INSTALL"); } } catch (Exception exception_log) { Console.Clear(); Console.Write("=======================================================================================================================\n"); Console.WriteLine(exception_log.ToString() + "\n"); Console.Write("=======================================================================================================================\n"); Console.WriteLine("FETCHING OR INSTALLATION ERROR - OPERATION FAILED"); Thread.Sleep(5000); } }
public WuStateSearching(IUpdateSearcher searcher, SearchCompletedCallback completedCallback, TimeoutCallback timeoutCallback, int timeoutSec) : base(WuStateId.Searching, "Searching Updates", timeoutSec, timeoutCallback, null) { if (searcher == null) { throw new ArgumentNullException(nameof(searcher)); } if (completedCallback == null) { throw new ArgumentNullException(nameof(completedCallback)); } _completedCallback = completedCallback; _searcher = searcher; }
static void CheckForUpdatesT() { try { if (EV.WaitOne(1000) == false) { return; } EV.Reset(); lst = new WUUpdateInfoList(); lst.List = new List <WUUpdateInfo>(); Status.Text = "Checking for updates (list only)"; UpdateSession UpdateSession = new UpdateSession(); UpdateSession.ClientApplicationID = "Fox SDC Update Controller"; IUpdateSearcher upd = UpdateSession.CreateUpdateSearcher(); ISearchResult res = upd.Search("IsInstalled=0 and Type='Software' and IsHidden=0"); if (res.Updates.Count == 0) { return; } for (int i = 0; i < res.Updates.Count; i++) { WUUpdateInfo wu = new WUUpdateInfo(); wu.Name = res.Updates[i].Title; wu.Description = res.Updates[i].Description; wu.Link = res.Updates[i].SupportUrl; wu.ID = res.Updates[i].Identity.UpdateID; lst.List.Add(wu); } return; } catch (Exception ee) { FoxEventLog.WriteEventLog("Failed to check for WU " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); lst = new WUUpdateInfoList(); lst.List = new List <WUUpdateInfo>(); return; } finally { Status.Text = "Idle"; EV.Set(); } }
/// <summary> /// Search online for Windows Updates /// </summary> public void CheckForUpdates() { uSession = new UpdateSession(); uSearcher = uSession.CreateUpdateSearcher(); uSearcher.Online = true; try { searchJob = uSearcher.BeginSearch("IsInstalled=0", new SearchCompletedFunc(this), null); } catch (Exception ex) { textBox1.Text = "Something went wrong: " + ex.Message; } }
public static UpdateCollection DownloadUpdates() { UpdateSession UpdateSession = new UpdateSession(); IUpdateSearcher SearchUpdates = UpdateSession.CreateUpdateSearcher(); ISearchResult UpdateSearchResult = SearchUpdates.Search("IsInstalled=0 and IsPresent=0"); UpdateCollection UpdateCollection = new UpdateCollection(); //Accept Eula code for each update for (int i = 0; i < UpdateSearchResult.Updates.Count; i++) { IUpdate Updates = UpdateSearchResult.Updates[i]; if (Updates.EulaAccepted == false) { Updates.AcceptEula(); } UpdateCollection.Add(Updates); } //Accept Eula ends here //if it is zero i am not sure if it will trow an exception -- I havent tested it. if (UpdateSearchResult.Updates.Count > 0) { UpdateCollection DownloadCollection = new UpdateCollection(); UpdateDownloader Downloader = UpdateSession.CreateUpdateDownloader(); for (int i = 0; i < UpdateCollection.Count; i++) { DownloadCollection.Add(UpdateCollection[i]); } Downloader.Updates = DownloadCollection; Console.WriteLine("Downloading Updates... This may take several minutes."); IDownloadResult DownloadResult = Downloader.Download(); UpdateCollection InstallCollection = new UpdateCollection(); for (int i = 0; i < UpdateCollection.Count; i++) { if (DownloadCollection[i].IsDownloaded) { InstallCollection.Add(DownloadCollection[i]); } } Console.WriteLine("Download Finished"); return(InstallCollection); } else { return(UpdateCollection); } }
private static void InstalledUpdates() { UpdateSession UpdateSession = new UpdateSession(); IUpdateSearcher UpdateSearchResult = UpdateSession.CreateUpdateSearcher(); UpdateSearchResult.Online = false; ISearchResult SearchResults = UpdateSearchResult.Search("IsInstalled=1 AND IsHidden=0"); //http://msdn.microsoft.com/en-us/library/windows/desktop/aa386526(v=VS.85).aspx foreach (IUpdate x in SearchResults.Updates) { Console.WriteLine($"{x.Title} issued {x.LastDeploymentChangeTime}"); } }
public static void UpdatesAvailable() { 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 remakrs section foreach (IUpdate x in SearchResults.Updates) { Console.WriteLine(x.Title); } }
private void Form1_Load(object sender, EventArgs e) { searcher = us.CreateUpdateSearcher(); searcher.Online = true; lblLoadingOverlay.Text = "Querying Windows Update ...\n(this may take a while)"; Task.Factory.StartNew(new Action(() => { installedUpdates = searcher.Search("(IsInstalled=1 OR IsInstalled=0) OR (IsPresent=1 OR IsPresent=0)").Updates; this.Invoke(new Action(async () => { lblLoadingOverlay.Text = "Loading blacklist ..."; await updateBlacklist(); lblLoadingOverlay.Visible = false; })); })); }
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); } }
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) ); }