c# - 如何在 .NET (C#) 中终止特定用户的进程?

标签 c# .net process

我在多用户 Windows Server 上工作,rdpclip 错误每天都困扰着我们。我们通常只是打开任务管理器并杀死然后重新启动 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 解决方案并不能帮助我得到它。

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

干杯, fr0man

最佳答案

我没有使用 GetProcessInfoByPID,而是从 StartInfo.EnvironmentVariables 获取数据。

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();
                }
            }
        }
    }
}

关于c# - 如何在 .NET (C#) 中终止特定用户的进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/426573/

相关文章:

c# - VS 项目设置正在构建一个没有 <appSettings> 或 <add> 元素的 .config 文件

c# - 如何确定我的 dll 的托管位置

c# - 来自 mysql 查询的组合框项目每秒刷新一次

c# - 当前上下文中不存在 TextToSplit

Java - 如何解析和处理复杂的XML

c# - 为什么 WPF 在我的案例中不选择正确的 DataTemplate?

.net - 将 .Net 远程处理与 ipv6 结合使用

.net - Directory.GetFiles 一次返回一个文件吗? (。网)

.net - Visual C++ - 使用 .net 终止进程

ruby - 讨论一个子进程,将 Ruby 与 IO 和线程一起使用