How to kill a specific user process on Windows Server?

3

I have a C # application that ultimately needs to kill a user process that ran, but as I am on a Terminal Server (Windows Server) and there are multiple logged in users, when I put the command to kill the process

Process[] processo = Process.GetProcessesByName("IEDriverServer");

    foreach (Process process in processo)
    {
        process.Kill();// finaliza processo
    }

It kills all users logged in to Terminal Server (Windows Server), is there any way to kill only the process of the user who ran my application?

    
asked by anonymous 11.08.2015 / 18:59

1 answer

1

According to this answer in SO you can do this:

    Process[] processlist = Process.GetProcesses();
    bool rdpclipFound = false;
    foreach (Process theprocess in processlist) {
        String ProcessUserSID = GetProcessInfoByPID(theprocess.Id);
        String CurrentUser = WindowsIdentity.GetCurrent().Name.Replace("SERVERNAME\",""); 
        if (theprocess.ProcessName == "rdpclip" && ProcessUserSID == CurrentUser) {
            theprocess.Kill();
            rdpclipFound = true;
        }
    }
    Process.Start("rdpclip");
    if (rdpclipFound) {
       MessageBox.Show("rdpclip.exe successfully restarted");
    } else {
       MessageBox.Show(@"rdpclip was not running under your username.
           It has been started, please try copying and pasting again.");
    }

Obviously you need some adaptations. There it is fixed what is the process. But I think I can see where it gets the user information and compares it to see if it is from the user or not and whether to kill it. There is another answer that does not use the current user. And it has link for other solutions.

Another solution closer to what you need with another approach in another response in OS .

static void KillProcessByNameAndUserName(string processName, string userName) {
    var processes = from p in Process.GetProcessesByName(processName)
                    where GetProcessOwner(p.Id) == userName
                    select p;
    foreach(Process p in processes) p.Kill();
}

static string GetProcessOwner(int processId) {
    string query = “Select * From Win32_Process Where ProcessID = “ + processId;
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
    ManagementObjectCollection processList = searcher.Get();
    foreach (ManagementObject obj in processList) {
        string[] argList = new string[] { string.Empty };
        int returnVal = Convert.ToInt32(obj.InvokeMethod(“GetOwner”, argList));
        if (returnVal == 0)
            return argList[0];
    }
    return “NO OWNER”;
}
    
11.08.2015 / 19:05