:: dostuff.bat
@echo off
:: insert long-running process call here
: End
What can I add to this batch file to make it terminate if it’s already running in another process when it’s executed?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well, if there can be only exactly one instance ever, then you can probably do this by creating a dummy file somewhere, probably in the temp directory:
you then remove it after you’re done:
and at the start of the batch file you can check whether that file exists and exit accordingly:
Similarly, you can do that by changing the window title, which should also be more robust against a Ctrl+C‘ed or crashed batch file.
Set the title:
Re-set it afterwards:
Check for it:
However, this has one problem: When cmd runs as administrator you’ll get “Administrator: DoStuff” as the title. Which doesn’t match anymore with
tasklist. You can hack-solve it by also checking for “Administrator: DoStuff” but that might look different depending on the Windows UI language, so it’s probably not the best solution.