简体   繁体   English

任务计划程序无法使用 PowerShell 脚本正确终止进程

[英]Task Scheduler can't kill a process properly using PowerShell script

I want to kill a process using Task Scheduler and PowerShell script.我想使用任务计划程序和 PowerShell 脚本杀死一个进程。 When a specific process starts, task scheduler triggers the PS script.当特定进程启动时,任务调度程序会触发 PS 脚本。 The script gets the process Id and tries to stop it.该脚本获取进程 ID 并尝试停止它。 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)请注意,我要杀死的进程也以管理员权限运行,并以 window 模式运行(不在后台)

Scheduled Task settings: running as SYSTEM with highest privileges.计划任务设置:以具有最高权限的 SYSTEM 运行。 I also used executionPloicyBypass parameter as below: powershell -ExecutionPolicy Bypass -File C:\Scripts\KillProcess.ps1 .我还使用了 executionPloicyBypass 参数,如下所示: 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.当我以管理员身份运行 PowerShell ISE 并在那里手动运行脚本时,它会立即终止该进程。 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?我对任务调度程序做错了吗?

I don't know what was the issue with Stop-Process but I changed it to process.Kill() method by getting the process object using Get-Process -Id $proc first.我不知道Stop-Process有什么问题,但我通过首先使用Get-Process -Id $proc进程 object 将其更改为process.Kill()方法。 Now it works without issue.现在它可以正常工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM