Created
May 17, 2020 16:29
-
-
Save SirJson/16e13ac99bf22798d38965e3a8d7b469 to your computer and use it in GitHub Desktop.
Cleanup your Workspace (almost)
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
#r "nuget:System.Management/4.7.0" | |
using System; | |
using System.Diagnostics; | |
using static System.Console; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Management; | |
Dictionary<string, string> procs = new Dictionary<string, string>(); | |
public string GetProcessOwner(int processId) | |
{ | |
string query = "Select * From Win32_Process Where ProcessID = " + processId; | |
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); | |
ManagementObjectCollection processList = searcher.Get(); | |
foreach (ManagementObject obj in processList) | |
{ | |
string[] argList = new string[] { string.Empty, string.Empty }; | |
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList)); | |
if (returnVal == 0) | |
{ | |
// return DOMAIN\user | |
return argList[1] + "\\" + argList[0]; | |
} | |
} | |
return "SYSTEM"; | |
} | |
foreach (var proc in Process.GetProcesses()) | |
{ | |
if (!procs.Keys.Contains(proc.ProcessName)) | |
{ | |
procs[proc.ProcessName] = GetProcessOwner(proc.Id); | |
} | |
} | |
var blacklist = new string[] { "conhost", "Agent", "ctfmon", "ApplicationFrameHost", "SearchUI", "RuntimeBroker", "dllhost", "CompPkgSrv", "sihost", "taskhostw", "dotnet", "RoslynPad", "explorer" }; | |
var list = procs.Where((b) => b.Value != "SYSTEM").Select(a => a.Key).Where(c => !c.Contains('.') && !c.StartsWith("Security") && !c.StartsWith("System") && !c.EndsWith("Host") && !blacklist.Contains(c)).ToList(); | |
var killcnt = 0; | |
foreach (var a in list) | |
{ | |
foreach (var z in Process.GetProcessesByName(a)) | |
{ | |
try | |
{ | |
z.Kill(true); | |
killcnt++; | |
} | |
catch (Exception e) | |
{ | |
WriteLine("Failed to kill {0}: {1}", a, e); | |
} | |
} | |
} | |
Console.WriteLine("Done! Killed {0} processes or children",killcnt); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment