2010-08-26 84 views
4

我正在嘗試編寫一個迷你w32可執行文件來遠程卸載使用WMI的應用程序。使用WMI遠程卸載應用程序

我可以列出以下使用此代碼已安裝的所有應用程序,但我不能找到一種方法來卸載遠程通WMI的應用程序和C#

我知道我可以使用MSIEXEC作爲一個過程做相同的,但我想解決這種使用WMI如果可能的...

感謝, 傑姆

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... 
     } 
    } 

} 
+0

Win32_Product類有一個卸載方法,並且很少有C++和PowerShell例子淨徘徊,但是我無法找到一個單一的使用c#中的win32_product類的示例和文檔。 – Nooneelse 2010-08-26 17:08:24

+0

順便說一下,關於使用WMI卸載遠程應用程序,至少還有兩個其他問題(使用示例代碼):http://stackoverflow.com/questions/2390268/using-wmi-to-uninstall-programs和http:/ /stackoverflow.com/questions/327650/wmi-invalid-class-error-trying-to-uninstall-a-software-on-remote-pc – Helen 2010-08-26 20:47:45

+0

對不起,你的時間,我想我有點疲憊和分心,同時搜索尋求答案。無論如何,感謝您的幫助。 – Nooneelse 2010-08-27 16:27:31

回答

13

看一看WMI Code Creator(來自微軟的免費工具)—它可以生成WMI鱈魚e爲您提供各種語言,包括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"]); 
} 
+2

+1分享代碼生成器! – mack 2013-07-19 15:35:27

+0

很多upvotes給你我的朋友!不知道有這樣的工具存在。 – slashp 2014-11-12 19:49:44