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

Lua脚本中PowerShell命令转义问题与子进程终止方案

在Lua中通过父进程PID终止子进程(PowerShell方案)

问题背景

需要在Lua脚本中实现根据父进程PID终止其子进程,优先使用PowerShell而非wmic。以下是已在Windows cmd.exe中验证可行的PowerShell命令:

powershell -Command "Get-WmiObject Win32_Process | Where-Object { $_.ParentProcessId -eq 311 } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }"

cmd /c "powershell -Command Get-WmiObject Win32_Process ^| Where-Object { $_.ParentProcessId -eq 311 } ^| ForEach-Object { Stop-Process -Id $_.ProcessId -Force }"

set PARENT_PID=311 && powershell -NoProfile -ExecutionPolicy Bypass -Command "$parentPID = [int]$env:PARENT_PID; Get-WmiObject Win32_Process | Where-Object { $_.ParentProcessId -eq $parentPID } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }"

但将这些命令通过Lua的os.execute()执行时完全无效,命令窗口一闪而过无任何输出,尝试多种转义方式仍无法解决问题。

问题排查与解决

最终定位到问题根源:传入的PID变量包含换行符。通过将命令写入批文件的方式排查格式问题,清理PID变量后成功解决。

解决代码示例

local sanitized_pid = job_pid:gsub("%s+", "")
local batch_file = system_directory .. "\\abort_job.bat"
local batch_content = "powershell -Command \"Get-WmiObject Win32_Process | Where-Object { $_.ParentProcessId -eq " .. sanitized_pid .. " } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }\"\n"
local file = io.open(batch_file, "w")
if file then
    file:write(batch_content)
    file:close()
    os.execute(batch_file)
else
    vlc.msg.err("Failed to create batch file for aborting job.")
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 22:45:55