简体   繁体   中英

Run MsiExec.exe from c++? Windows

MsiExec.exe /X{9BA100BF-B59D-4657-9530-891B6EE24E31};

I need to run this command through my cpp project in main. This is a new version of a piece of software that needs to remove the older version before installing. I want to do this using the Uninstall String from the application's registry. Is there a way to do this in cpp? I'm using Qt 5.5. Thanks.

One of the simplest ways is to use the system function.

Ie:

int result = system("MsiExec.exe /X{9BA100BF-B59D-4657-9530-891B6EE24E31}");

Other more Windows specific ways involve the use of CreateProcess or ShellExecute Windows Win32 API functions.

Is there a way to search out the uninstall key by looking in the registry for a matching DisplayName? Then, if you find the GUID by DisplayName, run the uninstall string like above? – RGarland

Of course there is. You can use native Windows API for manipulating registry or if you prefer you can use some existing C++ wrapper around that API.

I wrote small easy to use Registry wrapper which supports enumerating registry keys.

I think you may find it useful to solve your problem.

#include <Registry.hpp>

using namespace m4x1m1l14n;

std::wstring GetProductCodeByDisplayName(const std::wstring& displayName)
{
    std::wstring productCode;

    auto key = Registry::LocalMachine->Open(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");

    key->EnumerateSubKeys([&](const std::wstring& subKeyName) -> bool
    {
        auto subKey = key->Open(subKeyName);
        if (subKey->HasValue(L"DisplayName"))
        {
            if (displayName == subKey->GetString(L"DisplayName"))
            {
                // Product found! Store product code
                productCode = subKeyName;

                // Return false to stop processing
                return false;
            }
        }

        // Return true to continue processing subkeys
        return true;
    });

    return productCode;
}

int main()
{
    try
    {
        auto productCode = GetProductCodeByDisplayName(L"VMware Workstation");
        if (!productCode.empty())
        {
            //  Uninstall package
        }
    }
    catch (const std::exception& ex)
    {
        std::cout << ex.what() << std::endl;
    }

    return 0;

Also you should be aware , that some packages is not stored by its package code under Uninstall registry key, but by their names and to uninstall them you must search for UninstallString value within specific subkey and call this package instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM