Two ways to retrieve process id while startup a process via Windows command line

一个特殊的机缘, 需要通过cmd.exe启动一个进程, 并且获取该启动后进程的Process ID, 搜罗到两种方法:

1. 通过wmic process call create

  • wmic如果创建进程成功,将返回一个ReturnValue为0类JSON结构的输出, 从中获取ProcessId:
C:\app>cmd.exe /C wmic process call create "c:\app\cluster\GatewayServer.exe start -id 6", "c:\app"
Executing (Win32_Process)->Create()
Method execution successful.
Out Parameters:
instance of __PARAMETERS
{
        ProcessId = 19420;
        ReturnValue = 0;
};
  • wmic如果创建进程失败, 将返回一个ReturnValue非0的输出:
C:\app>wmic process call create "cluster\GatewayServer.exe start -id 6", "c:\app"
Executing (Win32_Process)->Create()
Method execution successful.
Out Parameters:
instance of __PARAMETERS
{
        ReturnValue = 9;
};

但wmic有一个很大的问题: 不使用当前用户上下文和系统的环境变量.

2. 通过powershell的Start-Process启动进程, 然后取Start-Process返回对像的Id属于得到Process ID:

C:\app>cmd.exe /C powershell -Command "try{$app = Start-Process -PassThru -FilePath \"cluster\GatewayServer.exe\" -WorkingDirectory \"C:\app\" -ArgumentList \"start -id 5\";echo $app.Id} catch {throw}"

Leave a Comment