Skip to content

Instantly share code, notes, and snippets.

@thepirat000
Last active April 20, 2022 03:01
Show Gist options
  • Save thepirat000/2d3b48cfda9d9ee94f3d00708825fa6a to your computer and use it in GitHub Desktop.
Save thepirat000/2d3b48cfda9d9ee94f3d00708825fa6a to your computer and use it in GitHub Desktop.
A powershell script to immediately terminate all the non-critical processes running
# Kill all non-essential processes
Add-Type -TypeDefinition @"
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
public static class WinProcess
{
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool IsProcessCritical(IntPtr hProcess, ref bool Critical);
public static List<Process> GetNonCritical()
{
return Process.GetProcesses()
.Where(p =>
{
try
{
if (p.HasExited)
{
return false;
}
bool isCritical = false;
var result = WinProcess.IsProcessCritical(p.Handle, ref isCritical);
return !result || !isCritical;
}
catch
{
return false;
}
})
.OrderBy(p => p.ProcessName)
.ToList();
}
};
"@
$doNotKill = "conhost", "svchost", "dllhost", "dwm","cmd", "explorer", "powershell", "wininit", "winlogon", "fontdrvhost", "lsass"
ForEach ($p in [WinProcess]::GetNonCritical())
{
if (-not $doNotKill.Contains($p.Name))
{
Write-Host $p.Name, $p.Handle
Stop-Process -Id $p.Id -Force
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment