How to determine whether a specific Windows Update

2020-06-23 08:40发布

问题:

I wonder how to determine whether a specific Windows Update package is installed in the target machine, lets say for example the Windows Update package with name KB2919355.

Exists a built-in feature to check that? If not, what would be the required code to determine it? Maybe messing with registry, or maybe a cleanest and/or secure way?

Pseudo-Code:

[Setup]
...

[Files]
Source: {app}\*; DestDir: {app}; Check: IsPackageInstalled('KB2919355')

[Code]
function IsPackageInstalled(packageName): Boolean;
  begin
    ...
    Result := ...;
  end;

回答1:

function IsKBInstalled(KB: string): Boolean;
var
  WbemLocator: Variant;
  WbemServices: Variant;
  WQLQuery: string;
  WbemObjectSet: Variant;
begin
  WbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
  WbemServices := WbemLocator.ConnectServer('', 'root\CIMV2');

  WQLQuery := 'select * from Win32_QuickFixEngineering where HotFixID = ''' + KB + '''';

  WbemObjectSet := WbemServices.ExecQuery(WQLQuery);
  Result := (not VarIsNull(WbemObjectSet)) and (WbemObjectSet.Count > 0);
end;

Use like:

if IsKBInstalled('KB2919355') then
begin
  Log('KB2919355 is installed');
end
  else 
begin
  Log('KB2919355 is not installed');
end;

Credits:

  • The WMI query for updates:
    How can I query my system via command line to see if a KB patch is installed?
  • Using WMI from Inno Setup:
    @TLama's answer to Inno Setup Pascal Script to search for running process.


回答2:

WbemScripting.SWbemLocator wasn't working for me when I was testing my installer on Windows 7. So I took a different approach and connected to the WUA (Windows Update Agent):

function IsUpdateInstalled(KB: String): Boolean;
var
  UpdateSession: Variant;
  UpdateSearcher: Variant;
  SearchResult: Variant;
  I: Integer;
begin
  UpdateSession := CreateOleObject('Microsoft.Update.Session');
  UpdateSearcher := UpdateSession.CreateUpdateSearcher()
  SearchResult := UpdateSearcher.Search('IsInstalled=1')
  for I := 0 to SearchResult.Updates.Count - 1 do
  begin
    if SearchResult.Updates.Item(I).KBArticleIDs.Item(0) = KB then
    begin
      Result := true;
      Exit;
    end;
  end;
  Result := false;
end;

Invocation would be as follows:

if IsUpdateInstalled('3020369') then
...