2013-06-04 86 views
2

我正在使用終端服務器上殺死進程iexplore(Internet Explorer)的應用程序。我遇到的問題是我殺死了終端服務器上的所有Internet Explorer進程,而不僅僅是當前用戶。用戶終止進程

因此,如果我以User1身份登錄並終止IE,它將被終止User2,User3等...我只希望User1的Internet Explorer被終止。我使用下面的代碼來殺死我的進程:

Private Sub ClearProcesses(ByVal ProcessName As String) 
    Dim myProcesses = Process.GetProcessesByName(ProcessName) 
    For Each Proc As Process In myProcesses 
     Try 
      Proc.Kill() 
     Catch ex As Exception 
      MsgBox(ex.Message, MsgBoxStyle.Critical, "ClearProcess") 
     End Try 
    Next 
End Sub 

有沒有辦法只殺死User1的進程?

回答

3

您可以使用WMI獲取進程的所有者,並驗證進程是否由當前用戶擁有。

使用功能,像這樣:

Public Function GetProcessOwner(processId As Integer) As String 
    Dim query As String = "Select * From Win32_Process Where ProcessID = " + processId 
    Dim searcher As New ManagementObjectSearcher(query) 
    Dim processList As ManagementObjectCollection = searcher.[Get]() 

    For Each obj As ManagementObject In processList 
     Dim argList As String() = New String() {String.Empty, String.Empty} 
     Dim returnVal As Integer = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList)) 
     If returnVal = 0 Then 
      ' argList(0) == User 
      ' argList(1) == DOMAIN 
      Return argList(0) 
     End If 
    Next 

    Return "NO OWNER" 
End Function 

你應該能夠做這樣的事情:

Private Sub ClearProcesses(ByVal ProcessName As String) 
    Dim myProcesses = Process.GetProcessesByName(ProcessName).Where(Function(p) GetProcessOwner(p.Id) = currentUser) 

    ' Your current code... 
+0

感謝您的答覆。 ManagementObject是.NET還是COM引用?我試圖找到它 – Alex

+0

@亞瑟.NET - System.Management.dll:http://msdn.microsoft.com/en-us/library/system.management.managementobject.aspx –

+0

謝謝我現在引用它。我收到一個錯誤:'重載解析失敗,因爲沒有可訪問的'Where'可以用這些爭論調用。我使用了以下代碼行: 'Dim myProcesses = Process.GetProcessesByName(ProcessName).Where(Sub(p)GetProcessOwner(p.Id)= System.Environment.UserName)' – Alex