2014-09-25 78 views
1

我正在使用WSManAutomation來遠程管理服務器。 我需要在啓用了WinRM的遠程服務器上安裝和卸載應用程序。連接不是問題使用WinRM和C卸載產品#

到目前爲止,下面的代碼在遠程主機上執行msiexec.exe,因爲我可以在進程列表中看到它,但它不執行卸載命令。

public void UninstallProduct(string path, string target, string username = null, string password = null) 
    { 
     IWSMan wsman = new WSManClass(); 
     IWSManConnectionOptions options = (IWSManConnectionOptions)wsman.CreateConnectionOptions(); 
     if (options != null) 
     { 
      try 
      { 
       options.UserName = username; 
       options.Password = password; 

       int iFlags = (int)_WSManSessionFlags.WSManFlagCredUsernamePassword; 
       IWSManSession session = (IWSManSession)wsman.CreateSession(string.Format("https://{0}:5986/wsman", target), iFlags, options); 
       // IWSManSession session = (IWSManSession)wsman.CreateSession(string.Format("http://{0}/wsman", target), 0, options); 
       if (session != null) 
       { 
        try 
        { 

         string strResource = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Process"; 
         string strInputParameters =string.Format("<p:Create_INPUT xmlns:p=\"{0}\"><p:CommandLine>\"{1}\"</p:CommandLine></p:Create_INPUT>", "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Process",path); 

         var reply = session.Invoke("Create", strResource, strInputParameters); 


         Console.WriteLine(reply); 
         Console.WriteLine(); 

        } 
        finally 
        { 
         Marshal.ReleaseComObject(session); 
        } 
       } 
      } 
      finally 
      { 
       Marshal.ReleaseComObject(options); 
      } 
     } 

    } 

到方法的調用上面會:

obj.UninstallProduct(@"C:\Windows\System32\msiexec.exe /x {E499AB77-9B27-416CB9B6F-4A171D02BB31} /passive", "hostname", @"hostname\Administrator", "password"); 

你知道爲什麼命令沒有得到執行? 我應該使用其他方式卸載產品嗎?

在此先感謝。

回答

0

最後我碰到一個辦法做到這一點使用遠程PowerShell來

string command = string.Format("(Get-WmiObject -Class Win32_Product | Where-Object {$_.Name -match {0}}).Uninstall()", productName); 

     PSCredential credential = new PSCredential(username, securePassword); 
     string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell"; 
     WSManConnectionInfo connectionInfo = new WSManConnectionInfo(true, target, 5986, "/wsman", shellUri, credential); 
     using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo)) 
     { 

      runspace.Open(); 

      Pipeline pipeline = runspace.CreatePipeline(command); 

      try 
      { 
       Collection<PSObject> results = pipeline.Invoke("Set-ExecutionPolicy Unrestricted -Scope Process"); 
      } 
      finally 
      { 
       runspace.Close(); 
      } 





     }