File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 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 }
You can’t perform that action at this time.
0 commit comments