Search code examples
windowsbatch-filecmdbatch-renamepowershell-cmdlet

How to close cmd in batch file


start cmd /k 

/k: is compulsory which will execute.

launching many command propmts can be done as below.

start cmd /k Call rc_hub.bat 4444

start cmd /k Call rc_grid1.bat 5555

start cmd /k Call rc_grid1.bat 6666

start cmd /k Call rc_grid1.bat 5570.

I want to know what cmd to be used for closing after launching

Eg: if %a="1234" start cmd /k Call rc_grid1.bat --> This is opening cmd , what cmd needs to give to close ?


Solution

  • Closing multiple instances of cmd is not a very uncommon task. It can arise, for example, when debugging some complex set of batch scripts.

    There is one of the ways to do this:
    First, give cmd windows unique titles. For example,

    start "unique_title" cmd.exe /k ...
    

    Second, when you want to close them, get process ids from tasklist output matching the titles. Then kill those ids with taskkill.

    tasklist /v /fo csv | findstr "unique_title"
    

    Here is the full example, the first argument is the title substring to match:

    kill_title.cmd

    @echo off
    set TITLE=unique_title
    if not "%~1"=="" set "TITLE=%~1"
    for /f "tokens=1,2,* delims=," %%a in ('tasklist /fi "imagename eq cmd.exe" /v /fo csv ^| findstr "%TITLE%"') do (
        rem here we check that the first column is "cmd.exe" ... just in case
        if "%%~a"=="cmd.exe" echo taskkill /pid "%%~b"
    )
    

    First check the script output, and if it is ok, remove echo before taskkill.