potisanのプログラミングメモ

趣味のプログラマーがプログラミング関係で気になったことや調べたことをいつでも忘れられるようにメモするブログです。はてなブログ無料版なので記事の上の方はたぶん広告です。記事中にも広告挿入されるみたいです。

C++ WILとWindows Update Agent APIでWindows Updateの更新履歴(タイトル、説明)を取得する

WILとWindows Update Agent APIでUpdateSearcherを作成・管理してWindows Updateの更新履歴からタイトルと説明を取得するサンプルコードです。タイトルと説明以外には日付等の難しい型が含まれるため、いったん無視しています。

// C++20

#include <iostream>
#include <vector>

#define STRICT
#define NOMINMAX
#include <Windows.h>
#include <wuapi.h>

#include <wil/com.h>
#include <wil/resource.h>

int main()
{
    // 日本語の出力設定
    std::wcout.imbue(std::locale("Japanese", std::locale::ctype));

    // COMの初期化。
    auto couninit = wil::CoInitializeEx_failfast(COINIT_APARTMENTTHREADED);

    // UpdateSearcherをIUpdateSearcherインターフェイスで作成する。
    auto updateSearcher = wil::CoCreateInstanceFailFast<UpdateSearcher, IUpdateSearcher>();

    // 更新履歴の数を取得する。
    LONG historyCount;
    FAIL_FAST_IF_FAILED(updateSearcher->GetTotalHistoryCount(&historyCount));

    // 更新履歴コレクションを作成する。
    wil::com_ptr_failfast<IUpdateHistoryEntryCollection> historyEntryCollection;
    FAIL_FAST_IF_FAILED(updateSearcher->QueryHistory(0, historyCount, &historyEntryCollection));

    // 更新履歴を列挙する。
    LONG entryCount;
    std::vector<wil::com_ptr_failfast<IUpdateHistoryEntry>> historyEntries;
    FAIL_FAST_IF_FAILED(historyEntryCollection->get_Count(&entryCount));
    historyEntries.resize(entryCount);
    for (LONG i = 0; i < entryCount; i++)
    {
        FAIL_FAST_IF_FAILED(historyEntryCollection->get_Item(i, &historyEntries[i]));
    }

    // 列挙した更新履歴を処理する。
    for (auto& historyEntry : historyEntries)
    {
        wil::unique_bstr title, description;
        FAIL_FAST_IF_FAILED(historyEntry->get_Title(&title));
        FAIL_FAST_IF_FAILED(historyEntry->get_Description(&description));

        std::wcout << wil::str_raw_ptr(title) << std::endl;
        std::wcout << wil::str_raw_ptr(description) << std::endl;
        std::wcout << std::endl;
    }

    return 0;
}