、ここでのJScriptのブロックを呼び出すためにcscript
を使用するバッチスクリプトです。 JScriptは新しい子プロセスを作成し、そのPIDを取得し、次にexplorer.exe
になるまで祖先のParentProcessID
行を歩き、直接の子のPIDを返します。 cmd.exe
またはcscript.exe
の複数のインスタンスが実行中であっても、スクリプトが実行されるコンソールウィンドウの正しいPIDを返す必要があります。
私は何と言うことができますか?今日私は創造的な気分でした。
@if (@[email protected]) @end /* JScript multiline comment
:: begin batch portion
@echo off
setlocal
for /f "delims=" %%I in ('cscript /nologo /e:Jscript "%~f0"') do (
echo PID of this console window is %%I
)
goto :EOF
:: end batch portion/begin JScript */
var oShell = WSH.CreateObject('wscript.shell'),
johnConnor = oShell.Exec('%comspec% /k @echo;');
// returns PID of the direct child of explorer.exe
function getTopPID(PID, child) {
var proc = GetObject("winmgmts:Win32_Process=" + PID);
// uncomment the following line to watch the script walk up the ancestor tree
// WSH.Echo(proc.name + ' has a PID of ' + PID);
return (proc.name == 'explorer.exe') ? child : getTopPID(proc.ParentProcessID, PID);
}
var PID = getTopPID(johnConnor.ProcessID);
johnConnor.Terminate();
// send the console window to the back for a second, then refocus, just to show off
oShell.SendKeys('%{ESC}');
WSH.Sleep(1000);
oShell.AppActivate(PID);
// output PID of console window
WSH.Echo(PID);