无法使用 WMI 终止进程,但 taskkill 有效 [英] can't terminate process using WMI but taskkill works

查看:47
本文介绍了无法使用 WMI 终止进程,但 taskkill 有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用户在管理员组中.我正在使用 .NET WMI API (System.Management) 使用以下代码终止进程:

My user is in the Administrators group. I am using the .NET WMI API (System.Management) to kill a process using this code:

var scope = new ManagementScope("\root\cimv2");
scope.Connect();
var query = new ObjectQuery(
    string.Format("Select * from Win32_Process Where ProcessID = {0}",
        processId));
var searcher = new ManagementObjectSearcher(scope, query);
var coll = searcher.Get().GetEnumerator();
coll.MoveNext();
var mgmtObj = (ManagementObject)coll.Current;
var ret = (uint) mgmtObj.InvokeMethod("Terminate");
// ret == 2 here, meaning "Access Denied"

它无法终止进程并返回 2(Access Denied).但是,如果我使用:

It's failing to kill the process and returning a 2 (Access Denied). However if I use:

Process.Start("cmd", string.Format("/c \"taskkill /f /pid {0}\"", processId));

进程被杀死.(但如果我省略 /f 它会失败).

the process gets killed. (but if I leave out /f it fails).

有没有办法使用 WMI 终止进程?

Is there any way to terminate the process using WMI?

我发现以下内容http://msdn.microsoft.com/en-us/library/windows/desktop/aa393907(v=vs.85).aspx:

要终止不属于您的进程,请启用SeDebugPrivilege 权限.

To terminate a process that you do not own, enable the SeDebugPrivilege privilege.

该页面提供了 VBScript 代码,但我将如何在 C# 中执行此操作?

The page provides VBScript code but how would I do this in C#?

推荐答案

这仅适用于某些 API 调用,这些 API 调用只能通过 pinvoke 使用 - 完整的 C# 源代码请参见 此处.

That is only possible with some API calls which are only available via pinvoke - for complete C# source code see here.

这篇关于无法使用 WMI 终止进程,但 taskkill 有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆