Windows – How to prevent the command prompt from closing after execution

batch filecommand linewindows

My problem is that in Windows, there are command line windows that close immediately after execution. To solve this, I want the default behavior to be that the window is kept open. Normally, this behavior can be avoided with three methods that come to my mind:

  1. Putting a pause line after batch programs to prompt the user to press a key before exiting
  2. Running these batch files or other command line manipulating tools (even service starting, restarting, etc. with net start xy or anything similar) within cmd.exe(Start – Run – cmd.exe)
  3. Running these programs with cmd /k like this: cmd /k myprogram.bat

But there are some other cases in which the user:

  1. Runs the program the first time and doesn't know that the given program will run in Command Prompt (Windows Command Processor) e.g. when running a shortcut from Start menu (or from somewhere else), OR
  2. Finds it a little bit uncomfortable to run cmd.exe all the time and doesn't have the time/opportunity to rewrite the code of these commands everywhere to put a pause after them or avoid exiting explicitly.

I've read an article about changing default behavior of cmd.exe when opening it explicitly, with creating an AutoRun entry and manipulating its content in these locations:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor\AutoRun
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Command Processor\AutoRun

(The AutoRun items are _String values_…)

I put cmd /d /k as a value of it to give it a try, but this didn't change the behaviour of the stuffs mentioned above at all… It just changed the behaviour of the command line window when opening it explicitly (Start-Run-cmd.exe).

So how does it work? Can you give me any ideas to solve this problem?

Best Answer

I have a solution which can only apply on .cmd and .bat files:

Open regedit and go to each one of:

[HKEY_CLASSES_ROOT\batfile\shell\open\command]
[HKEY_CLASSES_ROOT\cmdfile\shell\open\command] 

Now change the "Default key value" to cmd.exe /k "%1" %*. Now, every batch script window will stay open after its execution.

Note that this is like using cmd.exe /c cmd.exe /k program.bat, meaning that another CMD instance will be launched into the parent one. I couldn't find how to overwrite the first /c argument.

You can also do so with [exefile], but now it'll show an empty console box if the executable has a GUI.