【发布时间】:2017-07-28 11:15:44
【问题描述】:
我有一个控制台应用程序。我使用 WMI 来终止特定进程。 当我在 Visual Studio (IDE) 中运行此应用程序时,进程已成功终止。
我已经构建了应用程序,当我从命令提示符运行 exe 时,我得到了拒绝访问。
我正在以管理员身份运行 Visual Studio 和命令提示符 (cmd.exe)。
public static void WmiProcessHelper(string serverName, string processAction)
{
List<string> resultCode = null;
try
{
ConnectionOptions connectionOptions = new ConnectionOptions()
{
Impersonation = ImpersonationLevel.Impersonate,
};
ManagementScope scope = GetManagementScope(Root + serverName + WmiRootNamespace, connectionOptions);
scope.Connect();
string wmiQuery =
"SELECT * FROM Win32_process WHERE Name = 'dllhost.exe' AND CommandLine LIKE '%/Processid:{69F26581-22FB-4A52-9A7A-806760E3CB7D}%'";
ObjectQuery objectQuery = new ObjectQuery(wmiQuery);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, objectQuery);
ManagementObjectCollection objectCollection = searcher.Get();
foreach (ManagementBaseObject managementBaseObject in objectCollection)
{
if (resultCode == null)
{
resultCode = new List<string>();
}
ManagementObject process = (ManagementObject)managementBaseObject;
Console.WriteLine(string.Format("{0} the process.", processAction));
object returnObject = process.InvokeMethod(processAction, null);
if (returnObject != null)
{
int returnCode;
if (int.TryParse(returnObject.ToString(), out returnCode))
{
Console.WriteLine("Return Code = " + returnCode);
//resultCode.Add(GetProcessErrorMessage(returnCode));
}
}
}
if (resultCode == null)
{
Console.WriteLine("No Process with the given properties exists. ");
}
//return GetReturnMessage(resultCode, processAction);
}
catch (ManagementException e)
{
Console.WriteLine("Exception Occured: " + e.Message);
throw;
}
}`
【问题讨论】: