how do I kill all cmd.exe except the one currently running from batch?

MadsTheMan picture MadsTheMan · Apr 1, 2015 · Viewed 17.9k times · Source

The past few days I have been working on a script that I thought would be rather easy but it seems not, and I do understand why. My problem is how to get around it.

The batch script I need explained:

I have a script that runs in cmd.exe that does a bunch of things like moving a huge amount of files from a location to another. Lets call it movefile.cmd. This script works, but happens to stop sometimes (very rarely - lets not go into why and that script). Its important that this script always runs, so my idea here was to create a batch that exits cmd.exe and then re-opens the script each hour or so. Lets call this script restartcmd.bat

Sounds perfectly easy as I could do this:

@echo off

:loop

start c:\script\movefile.cmd 

Timeout /nobreak /t 3600

Taskkill cmd.exe

goto loop

But obviously this doesn't work because my new script also runs in cmd.exe, so it would kill this process as well.

What I've tried:

So I made a copy of cmd.exe and renamed it into dontkillthis.exe. I run dontkillthis.exe and then open the restardcmd.bat from dontkillthis.exe - this works perfectly! But I need to be able to just dobbleclick my script instead of doing that. Why? Because its supposed to be as easy as possible and I want my restartcmd.bat to be in my startup folder.

I've been looking at the ideas of getting the exact process ID of cmd.exe and shutting that so that my dontkillthis.exe will remain, but I can't seem to nail it. Tried all thats written in here how to kill all batch files except the one currently running , but I can't get it to work.

I'm not sure if I'm being confused or if it actually is a bit hard to do this.

I'd really appreciate some help here.

Best Regards

MO

Answer

npocmaka picture npocmaka · Apr 1, 2015

first you'll need the PID of the current CMD instance. The topic has been discussed here . I will offer you my solution - getCmdPID.bat

and here's the script (getCmdPID should in the same directory ):

@echo off

call getCmdPID
set "current_pid=%errorlevel%"

for /f "skip=3 tokens=2 delims= " %%a in ('tasklist /fi "imagename eq cmd.exe"') do (
    if "%%a" neq "%current_pid%" (
        TASKKILL /PID %%a /f >nul 2>nul
    )
)