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
相关产品推荐
相关产品推荐

