Command-Line-Interface

如何獲取與創建它的批處理文件和 cmd 程序關聯的 conhost 程序的 PID?

  • December 8, 2017

假設我有幾個恰好已經在執行的conhost程序。現在我執行一個批處理文件,該文件啟動一個cmd程序,該程序又導致另一個conhost程序打開。從批處理文件中

我的目標是能夠關閉之前(或可能在批處理文件執行之後)執行的所有其他conhost程序,而不是關閉與批處理文件關聯的conhostcmd.exe並執行所有關閉操作。如果那個conhost被關閉,它的cmd程序和批處理文件也會過早結束(我希望它在那之後做其他事情)。

這不是上面連結中提出的問題的重複。該問題僅涉及獲取pidof the cmd,而不涉及關聯的conhost PID

以下程式碼片段可能會導致解決方案:

@ECHO OFF
SETLOCAL EnableExtensions
::: get my own process ID - use any method
::: applied here: altered TonyRoth's answer https://serverfault.com/a/126643/257436
set "_title=a885974x%random%"
title %_title%
for /f "tokens=2" %%G in ('tasklist /V ^| findstr "%_title%"') do (
   set "_myProcessID=%%~G"
)

::: get the associated conhost process ID
set "_wQuery=ParentProcessId=%_myProcessID% and Name='conhost.exe'"
::: debug ::: wmic process where "%_wQuery%" get Name, ProcessId, WindowsVersion
for /f "usebackq" %%G in (`
 wmic process where "%_wQuery%" get ProcessId^, WindowsVersion^|findstr /R "[0-9]"
`) do set "_myConhostID=%%~G"

::: propagate results
set _my

引用自:https://serverfault.com/questions/885974