How to kill a specific user process on Windows Server?

Asked

Viewed 769 times

3

I have a C# application that at the end needs to kill a user process that ran, but as I am in a Terminal Server (Windows Server) and there are several users logged, 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), there is some way to kill only the process of the user who ran my application?

1 answer

1


According to this response in the OS 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.");
}

I put in the Github for future reference.

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

Another solution closer to what you need with another approach in another response in the 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”;
}

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.