How to find users executing processes

H

Han de Monnink

Hi,

I am looking for a way to determine het user that is running a certain
process, I can retrieve the process ID by calling the
GetProcessByName("test") method which will return all processes named
'test'.
But how do I retrieve the user that is running the process ( the process
'test' is started using the 'run as ' function provided in the user
interface of windows)?

Any help would be appreciated,


Han
 
W

Willy Denoyette [MVP]

| Hi,
|
| I am looking for a way to determine het user that is running a certain
| process, I can retrieve the process ID by calling the
| GetProcessByName("test") method which will return all processes named
| 'test'.
| But how do I retrieve the user that is running the process ( the process
| 'test' is started using the 'run as ' function provided in the user
| interface of windows)?
|
| Any help would be appreciated,
|
|
| Han
|
|
|
|

You can use System.Management and WMI for this. Just query the process list
using one of the process properties as serch criteria and call WMI's
GetOwner method on the instances returned.
Folling illustrates the process using a process name as query property.

GetProcessOwner("some.exe");

....
private static void GetProcessOwner(string procName)
{
SelectQuery selectQuery = new SelectQuery("select * from Win32_Process
where name='" + procName + "'");
using(ManagementObjectSearcher searcher = new
ManagementObjectSearcher(selectQuery))
{
ManagementObjectCollection processes = searcher.Get();
foreach(ManagementObject process in processes)
{
//out argument to return user and domain
string[] s = new String[2];
//Invoke the GetOwner method and populate the array with the user
name and domain
process.InvokeMethod("GetOwner",(object[])s);
Console.WriteLine("User: " + s[1]+ "\\" + s[0]);
}
}
}
}

Willy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top