Preface: I've boiled down a problem I'm having to this simple reproduction, which admittedly looks pretty strange out of context.
From powershell (PS), if I use Start-Process
to start notepad and capture the process ID, I can kill it with Stop-Process
, no problem:
PS > $x = Start-Process notepad.exe -PassThru
...
PS > Stop-Process $x.id
I can do the same with cmd.exe
, again without problem:
PS > $x = Start-Process cmd.exe -PassThru
...
PS > Stop-Process $x.id
Looking at TaskManager, this actually launches two processes: cmd.exe and conhost.exe. The PID returned from Start-Process
belongs to cmd.exe, and killing it via Stop-Process
terminates both.
However if I start a long-running sub-process like ping -t 127.0.0.1
within the console, stopping with Stop-Process
kills cmd.exe, conhost.exe, but leaves the window with ping.exe running, as if nothing was killed.
If instead I use taskkill /PID <process-id>
or terminate the process from TaskManager, all three processes (cmd, conhost, and ping) are terminated as expected.
Question
Why doesn't Stop-Process <pid>
terminate the process in the same way as taskkill /PID <pid>
? Is there any way to get Stop-Process
to terminate cmd.exe
and the long-running ping
subprocess?
Repro
Start cmd.exe from powershell and note the PID.
PS > $x = Start-Process cmd.exe -PassThru
PS > $x.id
23652
From the command prompt, start a long-running subprocess like ping:
> ping -t 127.0.0.1
Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
...
Open Task Manager and note the processes created in the same tree as ping.exe. For me these are:
Windows Command Processor
23652 cmd.exe
25260 conhost.exe
22140 PING.EXE
Attempt to terminate via the process id returned from Start-Process
:
PS > Stop-Process 23652
At this point, cmd.exe and conhost.exe are terminated, but TaskManager still shows ping
running as a top-level process.
TCP/IP Ping Command PING.EXE 22140
and the command prompt window remains, with the title C:\Windows\system32\cmd.exe - ping -t 127.0.0.1
.
Type CTRL+C from the "command prompt". PING will stop, and the window will disappear.