cmd.exe doesn't terminate when using a .bat file

kmote picture kmote · Mar 5, 2013 · Viewed 8.5k times · Source

[Context: I'm trying to create a shortcut to a .bat file with a relative "Start in" path as roughly described here and here.]

cmd.exe supports the /c switch. According to the documentation, this should cause it to "carry out the command and then terminate."

But the switch seems to be ignored when the command is a .bat file. For example, if you create a shortcut with the following Target (to a normal, non-bat command):

C:\Windows\System32\cmd.exe /c "START /d C:\temp\ notepad.exe test.txt"

Everything works as expected: Notepad opens and the console (shell) disappears. But if you replace the command above with a .bat file instead, like so:

C:\Windows\System32\cmd.exe /c "START /d C:\temp\ C:\test.bat"

(where test.bat contains only "notepad.exe test.txt") Notepad opens as before but the console sticks around like an unwanted friend. Why? And more to the point, How do I make it go away?

UPDATE: I know I can use wscript, as in this solution, but then I lose the option of having a custom icon (I'm stuck with the default .vbs icon).

Answer

Blorgbeard picture Blorgbeard · Mar 5, 2013

The start command begins a new process for the batch file. The original cmd.exe then terminates, but leaves the new process, which hangs around because it's waiting for notepad.exe to terminate.

Change your bat file contents to:

start "" notepad.exe test.txt

Then your batch file will not wait for notepad to exit before continuing execution.

Another thing to try:

C:\Windows\System32\cmd.exe /c "START /d C:\temp\ C:\test.bat & exit"

The nuclear option would be to write a small program in the (compiled) language of your choice that launches the .bat file and then exits. Then you can give it a custom icon, and make it do whatever you like.