Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save darianmiller/4df2423d57a83c903a3a410ce1e978bd to your computer and use it in GitHub Desktop.
Save darianmiller/4df2423d57a83c903a3a410ce1e978bd to your computer and use it in GitHub Desktop.
:: Source
:: Batch file example from May 2023 blog post: https://www.ideasawakened.com/post/prevent-concurrent-execution-batch-file-implementation-how-to
@echo off
::
:: Note - this extra call is to avoid a bug with %~f0 when the script
:: is executed with quotes around the script name.
::
:: %1 %2 %3 are example command-line parameters, include as desired
::
call :getLock %1 %2 %3
exit /b
:: Redirection
:: The Windows NT command processor interprets a single digit followed by a redirection
:: symbol as a request to redirect to the handle represented that single digit.
:: Handles 0, 1, and 2 are the standard input, standard output, and standard error, respectively.
:: In Powershell, 3,4,5,6 are used for warning,verbose,debug,info output, so we will use 9 as its currently undefined
::
:: Path
:: %~f0 expands to the fully qualified path of this batch file
::
:: Access
:: >> Opens the file in append mode and fails if already in use
::
:getLock
call :singleuser-main %1 %2 %3 9>>"%~f0"
exit /b
:singleuser-main
:: Body of your script goes here. Only one process can ever get here at a time.
:: The lock on this batch file will be released upon return from this routine,
:: or when the script terminates for any reason
echo %*
pause
@SilvoWeiss
Copy link

Well that was before I even started programming. And while my first "codding" attempts were actually with batch files I must admit that I haven't known about caret feature till today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment