使用WMI远程卸载应用程序

时间:2010-08-26 16:39:36

标签: c# wmi uninstall uninstaller wmi-query

我正在尝试使用WMI编写一个mini w32可执行文件来远程卸载应用程序。

我可以使用下面的代码列出所有已安装的应用程序,但我找不到通过WMI和C#远程卸载应用程序的方法

我知道我可以使用msiexec作为一个过程来做同样的事情,但我想用WMI解决这个问题,如果可能的话......

谢谢, 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 个答案:

答案 0 :(得分:13)

查看WMI Code Creator(来自Microsoft的免费工具) - 它可以为您生成各种语言的WMI代码,包括C#。

以下是说明Win32_Product.Uninstall方法用法的示例。您需要知道要卸载的应用程序的GUID,名称和版本,因为它们是Win32_Product类的关键属性:

...

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"]);

如果您有关于应用程序的部分信息(例如,只有名称或名称和版本),您可以使用SELECT查询来获取相应的Win32_Process对象:

...
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"]);
}