Last active
August 29, 2015 14:04
-
-
Save Romiko/0e0af3a04ff017ddfcb5 to your computer and use it in GitHub Desktop.
Kill Process for current user
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void KillProcesses(string processName, bool currentUserOnly, Process excludeMe = null) | |
{ | |
var processes = new ManagementObjectSearcher(string.Format("SELECT * FROM Win32_Process WHERE Name='{0}'", processName)).Get(); | |
foreach (var o in processes) | |
{ | |
var process = (ManagementObject)o; | |
var processId = int.Parse(process["ProcessId"].ToString()); | |
if (process["ExecutablePath"] == null) continue; | |
if (excludeMe != null && processId == excludeMe.Id) continue; | |
var ownerInfo = new object[2]; | |
process.InvokeMethod("GetOwner", ownerInfo); | |
var owner = (string)ownerInfo[0]; | |
if (currentUserOnly) | |
{ | |
var windowsIdentity = WindowsIdentity.GetCurrent(); | |
if (windowsIdentity == null) return; | |
var currentUser = windowsIdentity.Name; | |
if (currentUser.Contains(owner)) | |
process.InvokeMethod("Terminate", null); | |
} | |
else | |
process.InvokeMethod("Terminate", null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment