using WMI to uninstall applications remotely

2019-04-10 08:39发布

问题:

I am trying to write a mini w32 executable to remotely uninstall an application using WMI.

I can list all the installed applications using this code below but i couldnt find a way to uninstall the application remotely thru WMI and C#

I know I can do same using msiexec as a process but I wish to solve this using WMI if its possible...

Thanks, Cem

static void RemoteUninstall(string appname)
{
    ConnectionOptions options = new ConnectionOptions();
    options.Username = "administrator";
    options.Password = "xxx";
    ManagementScope scope = new ManagementScope("\\\\192.168.10.111\\root\\cimv2", options);
    scope.Connect();


    ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Product");

    ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
    ManagementObjectCollection queryCollection = searcher.Get();

    foreach (ManagementObject m in queryCollection)
    {
        // Display the remote computer information

        Console.WriteLine("Name : {0}", m["Name"]);

        if (m["Name"] == appname)
        {
            Console.WriteLine(appname + " found and will be uninstalled... but how");
            //need to uninstall this app...
        }
    }

}

回答1:

Have a look at WMI Code Creator (a free tool from Microsoft) — it can generate WMI code for you in various languages, including C#.

Here's an example illustrating the Win32_Product.Uninstall method usage. You need to know the GUID, name and version of the application you want to uninstall, as they are the key properties of the Win32_Product class:

...

ManagementObject app = 
    new ManagementObject(scope, 
    "Win32_Product.IdentifyingNumber='{99052DB7-9592-4522-A558-5417BBAD48EE}',Name='Microsoft ActiveSync',Version='4.5.5096.0'",
    null);

ManagementBaseObject outParams = app.InvokeMethod("Uninstall", null);

Console.WriteLine("The Uninstall method result: {0}", outParams["ReturnValue"]);

If you have partial info about the application (e.g. only name or name and version), you can use a SELECT query to obtain the corresponding Win32_Process object:

...
SelectQuery query = new SelectQuery("Win32_Product", "Name='Microsoft ActiveSync'");

EnumerationOptions enumOptions = new EnumerationOptions();
enumOptions.ReturnImmediately = true;
enumOptions.Rewindable = false;

ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, options);

foreach (ManagementObject app in searcher.Get())
{
    ManagementBaseObject outParams = app.InvokeMethod("Uninstall", null);

    Console.WriteLine("The Uninstall method result: {0}", outParams["ReturnValue"]);
}