You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何终止通过Task Scheduler与PowerShell启动的指定Python.exe进程

解决Python进程残留:终止本次启动的特定实例

问题背景

之前通过Task Scheduler执行.bat文件运行Python脚本,Windows虚拟机系统更新后该方式失效。调整为:Task Scheduler调用.bat文件,由.bat以管理员权限启动PowerShell脚本,再通过PowerShell调用Python脚本。但目前遇到Python.exe进程残留问题,且不能终止所有Python实例,需仅终止本次启动的进程。

当前脚本内容

.bat文件(存在参数错误)

Powershell.exe -executionpolicy Unrestricted -File  C:\Users\UserName\Desktop\PsPythonTest\runPythonScript.ps1 -Verb RunAs

PowerShell脚本(存在冗余启动)

$path = 'C:\Users\UserName\Desktop\PsPythonTest\test.py'

start-process PowerShell -verb runas

python $path

修正方案

1. 修正.bat文件(正确以管理员权限启动PowerShell脚本)

原.bat中-Verb RunAs是无效参数,需用Start-Process实现权限提升:

@echo off
Start-Process Powershell.exe -ArgumentList "-executionpolicy Unrestricted -File C:\Users\UserName\Desktop\PsPythonTest\runPythonScript.ps1" -Verb RunAs

2. 修改PowerShell脚本(跟踪并管理本次启动的Python进程)

去掉冗余的PowerShell启动,直接启动Python并捕获进程对象,确保仅终止当前实例:

# 定义Python路径和脚本路径,若python不在系统环境变量,需填写完整路径(如C:\Python310\python.exe)
$pythonExe = "python"
$scriptPath = "C:\Users\UserName\Desktop\PsPythonTest\test.py"

# 启动Python进程,获取进程对象以便后续管理
$pythonProcess = Start-Process -FilePath $pythonExe -ArgumentList $scriptPath -PassThru -Verb RunAs

# 等待Python脚本执行完成(可选,若需脚本执行完再后续操作则保留)
$pythonProcess.WaitForExit()

# 若进程未正常退出,强制终止该特定进程(仅针对本次启动的实例)
if (-not $pythonProcess.HasExited) {
    Stop-Process -Id $pythonProcess.Id -Force
}

说明

  • 通过-PassThru参数捕获启动的Python进程对象,可精准操作该实例,不会影响其他运行中的Python进程。
  • -Verb RunAs确保Python脚本以管理员权限运行,匹配需求场景。
  • WaitForExit()会等待脚本执行完毕,若无需等待可移除,但建议保留以确保进程正常结束后再处理。

内容的提问来源于stack exchange,提问作者ortunoa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 21:50:36