Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for wholocked.bat

(view source code of wholocked.bat as plain text)

  1. @ECHO OFF
  2. :: Check command line arguments
  3. IF       "%~1"==""   GOTO Syntax
  4. IF       "%~1"=="/?" GOTO Syntax
  5. IF NOT   "%~2"==""   GOTO Syntax
  6. IF NOT EXIST "%~1"   GOTO Syntax
  7. :: Check if handle.exe is available
  8. HANDLE.EXE /? >NUL 2>&1 || GOTO Syntax
  9.  
  10.  
  11. SETLOCAL ENABLEDELAYEDEXPANSION
  12. FOR /F "tokens=1,2 delims=:" %%A IN ('HANDLE.EXE -nobanner -accepteula "%~1"') DO (
  13.     SET LockingProg=%%A
  14.     SET LockingProg=!LockingProg: pid=!
  15. )
  16. :: Remove trailing spaces
  17. :WhileLoop
  18. IF "%LockingProg:~-1%"==" " (
  19.     SET LockingProg=%LockingProg:~0,-1%
  20.     GOTO WhileLoop
  21. )
  22.  
  23. ECHO "%~1" is blocked by %LockingProg%
  24. ECHO Do you want to ←[0;1;31mC←[0mlose it, ←[0;1;31mK←[0mill it or ←[0;1;31mI←[0mgnore it? [CKI]
  25. CHOICE.EXE /C CKI /N /D I /T 30
  26. SET Choice=%ErrorLevel%
  27.  
  28. IF %Choice%  EQU 1 (
  29.     TASKKILL.EXE /IM %LockingProg%
  30. )
  31.  
  32. IF %Choice% EQU 2 (
  33.     TASKKILL.EXE /IM %LockingProg% /F
  34. )
  35.  
  36. ENDLOCAL
  37. EXIT /B 0
  38.  
  39.  
  40. :Syntax
  41. ECHO.
  42. ECHO WhoLocked.bat,  Version 1.00
  43. ECHO Check which program keeps a file or folder locked and optionaly unlock it
  44. ECHO.
  45. ECHO Usage:   ←[0;1mWhoLocked.bat  file_or_folder←[0m
  46. ECHO.
  47. ECHO Where:   ←[0;1mfile_or_folder←[0m is the file or folder being locked
  48. ECHO.
  49. ECHO Notes:   This batch file uses Mark Russinovich's HANDLE.EXE, available at
  50. ECHO          ←[0;1;30mhttps://learn.microsoft.com/en-us/sysinternals/downloads/handle←[0m
  51. ECHO          to check which program keeps the file or folder open.
  52. ECHO          Though this could also be achieved with Windows' native
  53. ECHO          OPENFILES.EXE, HANDLE.EXE does not require elevated privileges
  54. ECHO          whereas OPENFILES.EXE does.
  55. ECHO          This batch file uses Windows' native TASKKILL.EXE to terminate
  56. ECHO          the blocking program. This could also be achieved with HANDLE.EXE,
  57. ECHO          but that would require elevated privileges, whereas TASKKILL.EXE
  58. ECHO          does not.
  59. ECHO          The batch file gives you a choice to close the locking program
  60. ECHO          gracefully, or to kill it by force, or to ignore it and do nothing.
  61. ECHO          In case multiple programs keep the file or folder locked, only the
  62. ECHO          ←[0;1mlast one found←[0m is displayed, so you may have to run this batch file
  63. ECHO          multiple times.
  64. ECHO.
  65. ECHO Written by Rob van der Woude
  66. ECHO https://www.robvanderwoude.com
  67.  
  68. EXIT /B 1
  69.  

page last modified: 2024-04-16; loaded in 0.0078 seconds