How to Prevent Batch File From Closing Automatically

The command prompt, once launched, will only close when the user types the exit command or click the close window button. But it also happens that the command prompt closes itself. That happens without showing the results of the completed script. This behavior of the console can be spotted when executing script files, such as CMD and BAT files.

This is by design and there is nothing wrong with the default behavior. But sometimes it is necessary to keep the console open after running the script from File Explorer. For example, to waits for the next command to be entered, or to read some output.

Well, changing the command prompt behavior is a very easy task. The easiest way is to add a pause command or a special argument to the end of the batch file that starts a new instance of the command prompt.

Open the batch file in Notepad or any other text editor, and one of the following commands to the end of the file:

  • pause
  • cmd /k

Save the file. These are two different methods and they work differently.

The pause command

Add Pause Command

The pause command interrupts the execution of the script and displays the message “Press any key to continue…”. If the command is added to the end of the script, pressing any key will close the console, but if pause is in the middle of the code, after pressing any key, the execution of the script will continue to the below lines.

Cmd /k command

Add Cmd K Command

When added to the end of the script, it starts a new console, displaying the standard prompt for a new command.

If you add cmd /k in the middle of the batch file, its execution will be interrupted and terminated.

This is the key difference between these commands.

If you don’t want to mess around with each batch file, you can change the default execution command for batch files in the registry.

How to prevent any batch file from closing by default

  • Open the registry editor with the regedit command.
  • Expand the HKCR\batfile\shell\open\command branch.
  • Change the default unnamed value in the right side from "%1" %* to cmd.exe /k "%1" %*.Prevent Batch File From Closing Automatically
  • Now do the same under the HKCR\cmdfile\shell\open\command key.

That’s all. From now on any batch file will end up with a command prompt when launched from the File Explorer. It will have to be closed only by the user, unless the exit command is explicitly included in the batch file.

Looks like you've read the post to the end. If you enjoyed it, please share it. You would greatly help our blog to grow!

Author: The MFTNEXT Team

The MSFTNEXT project is a small team of authors who love to engage with the latest technology and gadgets. Being passionate Windows bloggers, we are happy to help others fix their system issues.

Leave a Reply

Your email address will not be published.

css.php