indows Management Instrumentation (WMI) 是 Windows 操作系统的一个组件,允许通过编程方式访问企业环境中的管理信息。
当然,WMI也能获得远程机器的进程列表和根据进程ID获取进程的用户名
需要添加对 System.Management.dll 的引用
using System.Diagnostics;
using System.Management;
static void Main(string[] args)
{
foreach(Process p in Process.GetProcesses())
{
Console.Write(p.ProcessName);
Console.Write("----");
Console.WriteLine(GetProcessUserName(p.Id));
}
}
private static string GetProcessUserName(int pID)
{
string text1 = null;
SelectQuery query1 = new SelectQuery("Select * from Win32_Process WHERE processID=" + pID);
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(query1);
try
{
foreach (ManagementObject disk in searcher1.Get())
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
inPar = disk.GetMethodParameters("GetOwner");
outPar = disk.InvokeMethod("GetOwner", inPar, null);
text1 = outPar["User"].ToString();
break;
}
}
catch
{
text1 = "SYSTEM";
}
return text1;
}