2009-01-09 29 views
5

我使用的是多用戶Windows Server,而rdpclip的bug每天都會讓我們大吃一驚。我們通常只需打開任務管理器並殺死然後重新啓動rdpclip,但這是一個令人頭疼的問題。我寫了一個powershell腳本來殺死然後重新啓動rdpclip,但是沒有人使用它,因爲它是一個腳本(更不用說執行策略限制了這個框)。我試圖寫一個快速和髒的Windows應用程序,你點擊一個按鈕來殺死rdpclip並重新啓動它。但是我想限制它到當前用戶,並且找不到Process類的方法。到目前爲止,這裏是我有:如何在.NET(C#)中爲特定用戶終止進程?

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

回答

6

好吧,這是我落得這樣做:

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

      } 
1

閱讀下面的CodeProject上的文章,它的所有信息,你需要:

How To Get Process Owner ID and Current User SID

+0

看起來不錯,除非我無法使用VS來識別ObjectQuery,即使使用System.Management也是如此。這是我完全不熟悉的一個領域。 – fr0man 2009-01-09 00:32:17

+0

啊,沒關係。這僅在.NET 2.0及以下版本中受支持。現在修復。 – fr0man 2009-01-09 00:35:14

3

In代替使用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(); 
       } 
      } 
     } 
    } 
}