I have authored a batch script that assumes %1 is a path to a file. At times I would like to use this batch script via drag-drop in Windows Explorer (dragging my target file onto my batch script file), and at other times I would like to run this batch script from an existing command prompt window and provide my %1 path explicitly (usually just a relative path).

I don't want my script to disappear immediately when "drag dropping", thus I need to pause. However, I don't want to have to press any key to continue every time when using an existing command prompt window, thus I don't want pause.

Is there a way to have the best of both worlds? Can I somehow detect/infer the scenario I'm in, and decide to pause or not pause thereafter? What's the best approach here?


Try using this in your batch file:

set arg0=%0
if [%arg0:~2,1%]==[:] pause

This checks whether the 3rd character of the 0th argument (basically, the batch file name itself) is a colon or not.

Normally, when you drag-and-drop something on a batch file, it's called as: "Drive:\path\to\Batch File.bat" Arg1 Arg2 ... However, when we execute a batch file from the Command Prompt we generally do not tend to call it like that, with a quoted absolute path. Thus we can exploit this difference and execute a pause only when the colon exists as the 3rd character, implying that the batch file was executed via drag-and-drop. Of course, if you do use a quoted absolute path to execute the batch file from the command prompt, it will naturally pause as well.

  • Exactly what I need. – DuckMaestro Jan 4 '13 at 4:27

Throw a cmd /k at the end of your script. In an existing window it will just return to the command prompt, and in a new window it will do the same, keeping the window open.

@echo off
echo "some text"
cmd /k

Note the /k is to stop it printing the:

Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved.

  • +1. This is helpful, though this has the side effect of now leaving open a command prompt, when really I'd like to keep the behavior of pause in that I can simply hit spacebar (or any key) to close the new window. – DuckMaestro Jan 4 '13 at 2:17
  • How about Alt+F4? :P I don't think there's really any way to differentiate between the two situations unfortunately. Happy for someone to prove me wrong though, would be useful. – Taz Jan 4 '13 at 2:19
  • Haha, I actually just tried to close a command prompt with Alt+F4 to discover it doesn't work. -.- – Taz Jan 4 '13 at 2:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.