正在使用WinRM和C#卸载产品
本文关键字:卸载 WinRM | 更新日期: 2023-09-27 18:24:25
我正在使用WSManAutomation远程管理服务器。我需要在启用了HTTPS上的WinRM的远程服务器上安装和卸载应用程序。连接不是问题
到目前为止,下面的代码在远程主机中执行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");
你知道为什么命令没有被执行吗?我应该使用其他方式卸载产品吗?
提前谢谢。
最后,我找到了一种使用远程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();
}
}