4 April 2012

Query KB updates installed in Window 7

Prior to Windows Vista, WMI's Win32_QuickFixEngineering class was used for querying the KB updates installed in the system. But, Starting with Windows Vista, win32_QuickFixEngineering returns only the updates supplied by Component Based Servicing (CBS). It will not return updates installed by MSI or Windows Updates. Read this page for more info. So, to query the updates installed via MSI or Windows Updates, you can use Windows Update Agent Object Model. Here I am going to show you, how to query the installed KB updates in C#.

We begin by adding reference to Wuapi.dll. You can do that by selecting "WUAPI 2.0 Type Library" from COM tab in Add Reference dialog in Visual Studio.


Once you add reference to Wuapi.dll, you can create an object of WUApiLib.UpdateSession class. This class cab be used by the caller to perform operations that involve updates, such as download, install or search for updates. Once you have UpdateSession object ready, you can call QueryHistory on it to get history of installed updates. Let me show you the code directly.

WUApiLib.UpdateSession session = new UpdateSession();
IUpdateSearcher us = session.CreateUpdateSearcher();

var updatesCollection = session.QueryHistory(String.Empty, 0, us.GetTotalHistoryCount());
for (int i = 0; i < updatesCollection.Count; i++)
{
    Console.WriteLine(coll[i].Title);
}

Note that, the list of updates resulted from above code may not match with the list of updates in Add/Remove Programs window in control panel.  The missing updates might be installed via Component Based Servicing or they are non-microsoft updates.

References:
  •  Searching, Downloading, and Installing Updates (link)
  •  Using the Windows Update Agent API (link)