I have a number of Windows 7 PC's that need patching with a particular Windows update, using the Windows Update API in a C# console app. The API needs to search the installed updates and report back if it's already installed and perform the installation if not.
Whilst testing on a Virtual PC (Windows 7 Professional Hyper-v client) I have a situation similar to the target PCs (Windows 7 Embedded) where the following code returns (very quickly and without any exceptions) 0 updates. Which I know to be wrong. In fact, it even returns this after I install a .msu update.
Code:
UpdateSession uSession = new UpdateSession();
IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
uSearcher.Online = false;
try
{
ISearchResult sResult = uSearcher.Search("IsInstalled=1 And IsHidden=0");
Console.WriteLine("Found " + sResult.Updates.Count + " updates");
foreach (IUpdate update in sResult.Updates)
{
Console.WriteLine(update.Title);
if (update.Title.ToLower().Contains("kb123456")) {
//Update is not required
ReportInstalled();
return;
}
}
//If we get here, the update is not installed
InstallUpdate();
}
catch (Exception ex)
{
Console.WriteLine("Something went wrong: " + ex.Message);
}
Now for the fun part. If I open up the Windows Update from the Control Panel and click 'Check for updates', it goes off for a while and comes back with a bunch of updates to install. At this point, if I run the above code, it works as expected and reports over 200 installed updates.
It appears that the manual process of searching for updates starts/restarts some services and/or other processes, however, I am struggling to figure out exactly what I need to do to the system to get it into the correct state. I expect the answer will be a simple case of starting service x or process y with a set of args, but which?
Some (not all) of the things I have tried but did not alter the behavior:
- Started the BITS service, restarted Windows Update Service
- Tried launching wuauclt.exe with various switches (documented here in the comments)
With the machine in a state where the code runs correctly (after I run WU manually), I have noticed the process wuauclt.exe appears to start when the above code is run. When it's in the target state (before I run WU manually), wuauclt.exe does not start, and I am not able to launch this manually, I suspect this is a big clue.
One other clue is the state of Windows Update before I run it manually. In the control panel windows update looks like this:
After running WU and installing updates via that method, and the machine is in a state where the code runs as expected WU looks like:
To sum up, I need this process to automate the installation of an update. If I detect 0 installed updates, I know the machine is in a particular state, so I will need to launch/restart some processes and services (programmatically) to get the machine into the correct state before running my code. Knowing what to run/restart is the essence of this problem.