Skip to content

Commit 6d0bfef

Browse files
committed
Add script to kill processes by patterns on Windows.
1 parent 2efdedd commit 6d0bfef

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
param(
2+
[Parameter(Mandatory=$true)]
3+
[string[]]$Patterns
4+
)
5+
6+
# For each pattern, find processes where CommandLine contains the pattern, then terminate them.
7+
# Uses CIM (Get-CimInstance) instead of WMIC. Works on PowerShell 5.1 and later.
8+
9+
$errors = @()
10+
foreach ($p in $Patterns) {
11+
try {
12+
# Escape single quotes in pattern for WQL-like contains by using simple substring match in PowerShell
13+
$pat = $p
14+
$matches = Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and ($_.CommandLine -like "*$pat*") }
15+
foreach ($proc in $matches) {
16+
try {
17+
Write-Host "Terminating pid=$($proc.ProcessId) cmdline='$($proc.CommandLine)'"
18+
$rc = $proc | Invoke-CimMethod -MethodName Terminate
19+
if ($rc.ReturnValue -ne 0) { Write-Warning "Terminate returned $($rc.ReturnValue) for pid $($proc.ProcessId)" }
20+
} catch {
21+
Write-Warning "Failed to terminate pid $($proc.ProcessId): $_"
22+
$errors += $_
23+
}
24+
}
25+
} catch {
26+
Write-Warning "Error querying processes for pattern '$p': $_"
27+
$errors += $_
28+
}
29+
}
30+
31+
if ($errors.Count -gt 0) { exit 2 } else { exit 0 }

0 commit comments

Comments
 (0)