I want to kill a process using Task Scheduler and PowerShell script. When a specific process starts, task scheduler triggers the PS script. The script gets the process Id and tries to stop it. My issue is, the script can't kill the process until the process finishes its job. However, I want to kill the process as soon as the script triggers, without waitingfor anything. As a note, the process I want to kill also runs with Admin privileges, and runs in window mode(not in background)
Scheduled Task settings: running as SYSTEM with highest privileges. I also used executionPloicyBypass parameter as below:
powershell -ExecutionPolicy Bypass -File C:\Scripts\KillProcess.ps1.
In the script, I have the following code basically
$process = Get-Process -Id $pid
$process.PriorityClass = 'High'
$events=Get-WinEvent -FilterHashtable @{LogName="Security"; Id = <eventId>; StartTime = [datetime]::Now.AddMinutes(-5)} |Where-Object -Property Message -Match '<string to search for>' | Where-Object -Property Message -Match ('<string to search for>') -ErrorAction Stop
if (!$events[0].message) {
Exit
}
else {
$processes = @()
#for each event, get process Id and kill it.
#this is because the process can spawn multiple process.
foreach ($event in $events) {
#parse the process Id.-*
$processId=[int][regex]::Match($event.message,'Process\sID\:\s+(0x.+)\s').captures.groups[1].Value
$processes += $processId
}
$processes = $processes | Select -Unique
foreach ($proc in $processes) {
Stop-Process -Id $proc -Force -ErrorAction SilentlyContinue
}
}
When I run PowerShell ISE as Admin and run the script there manually, it immediately kills the process. However, it waits for the process to finish its job when task scheduler triggers the script. Am i doing something wrong with the Task scheduler?