你如何在.NET(C#)中杀死特定用户的进程?

我使用的是多用户Windows Server,rdpclip bug每天都会让我们感到害怕。 我们通常只是打开任务管理器并杀死然后重新启动rdpclip,但这是一个痛苦的屁股。 我写了一个powershell脚本用于杀死然后重新启动rdpclip,但是没有人使用它,因为它是一个脚本(更不用说执行策略仅限于框)。 我正在尝试编写一个快速而又脏的Windows应用程序,您可以单击按钮来杀死rdpclip并重新启动它。 但是我想将它限制为当前用户,并且找不到执行此操作的Process类的方法。 到目前为止,这就是我所拥有的:

Process[] processlist = Process.GetProcesses(); foreach(Process theprocess in processlist) { if (theprocess.ProcessName == "rdpclip") { theprocess.Kill(); Process.Start("rdpclip"); } } 

我不确定,但我认为这会杀死所有的rdpclip进程。 我想按用户选择,就像我的powershell脚本一样:

 taskkill /fi "username eq $env:username" /im rdpclip.exe & rdpclip.ex 

我想我可以从我的可执行文件中调用powershell脚本,但这看起来相当糟糕。

对于任何格式问题都要提前道歉,这是我第一次来这里。

更新:我还需要知道如何获取当前用户并仅选择那些进程。 下面提出的WMI解决方案对我没有帮助。

UPDATE2:好的,我已经弄清楚如何获取当前用户,但它与远程桌面上的进程用户不匹配。 任何人都知道如何获得用户名而不是SID?

干杯,fr0man

好的,这就是我最终做的事情:

  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."); } } 

我只是从StartInfo.EnvironmentVariables中获取数据,而不是使用GetProcessInfoByPID。

 using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Security.Principal; using System.Runtime.InteropServices; namespace KillRDPClip { class Program { static void Main(string[] args) { Process[] processlist = Process.GetProcesses(); foreach (Process theprocess in processlist) { String ProcessUserSID = theprocess.StartInfo.EnvironmentVariables["USERNAME"]; String CurrentUser = Environment.UserName; if (theprocess.ProcessName.ToLower().ToString() == "rdpclip" && ProcessUserSID == CurrentUser) { theprocess.Kill(); } } } } } 

阅读以下CodeProject文章,它包含您需要的所有信息:

如何获取进程所有者ID和当前用户SID