Skip to main content

How to Run a Cleanup Routine Before Script Exits in Batch Script

Professional scripts often create temporary files, map network drives, or start background processes that should not remain on the system once the work is done. If a user manually closes the script or it crashes due to an error, these "leftovers" can cause disk clutter or security vulnerabilities. A "Cleanup Routine" is a dedicated section of code that ensures the system is returned to its original state before the script terminates.

This guide will explain how to implement a reliable cleanup routine using labels and exit traps.

1. The Basic Cleanup Label

The simplest way to implement a cleanup routine is to have all exit points in your script jump to a single :CLEANUP label.

@echo off
setlocal

set "TempDir=%temp%\MyScript_Working"
if not exist "%TempDir%" mkdir "%TempDir%"

echo [INFO] Performing tasks...
:: (Do work here)

:: Success Exit
echo [SUCCESS] Task finished.
goto :CLEANUP


:CLEANUP
echo [SYSTEM] Cleaning up temporary files...
if exist "%TempDir%" rd /s /q "%TempDir%"
pause
endlocal
exit /b

2. The Error-Aware Cleanup

Often, you want to perform cleanup even when an error occurs. You can integrate this with your error handling logic.

@echo off
setlocal

net use Z: \\SERVER\Share >nul 2>&1
if %errorlevel% neq 0 (
echo [ERROR] Could not map drive.
set "ExitCode=1"
goto :CLEANUP
)

:: (Main logic here)
set "ExitCode=0"

:CLEANUP
echo [SYSTEM] Disconnecting network drives...
net use Z: /delete /y >nul 2>&1

echo [SYSTEM] Script finished with code %ExitCode%.
endlocal & exit /b %ExitCode%

3. Handling Manual Closures (Limit)

warning

The CMD Limitation. Pure Windows Batch does not have a native "Trap" function (like in Bash) to catch a user clicking the 'X' on the window. If the window is closed forcefully, the cleanup code will NOT run.

The Workaround: For critical systems, wrap your main script in a parent supervisor. The parent script waits for the child to end, and then the parent performs the cleanup regardless of how the child died.

@echo off
setlocal

:: This is the 'Wrapper' script
call main_task.bat

:: This part runs even if main_task.bat crashes (but not if THIS window is closed)
echo [CLEANUP] Guardian process cleaning up...
del "%temp%\*.tmp" >nul 2>&1

endlocal
exit /b

How to Avoid Common Errors

Wrong Way: Cleaning up as you go

If you delete temp file A as soon as you are done with it, but the script crashes 5 minutes later while working on file B, file B will stay on the drive forever.

Correct Way: Dedicate a single folder for all your script's temporary assets and delete the entire folder in one command at the very end.

Problem: RD /S /Q failing

If an application still has a file open in your temporary folder, the rd /s /q command will fail because the folder is "in use."

Solution: Use a short timeout /t 2 before the cleanup to allow applications time to release their file locks.

Best Practices and Rules

1. The "Leave No Trace" Rule

If your script changes the command prompt color or window title, reset them in the cleanup block. color 07 title Command Prompt

2. Quiet Cleanup

Use >nul 2>&1 for all cleanup commands. If a file was already deleted or a drive was never mapped, the user doesn't need to see "File Not Found" errors during the cleanup phase.

3. Local Variable Cleanup

Always use setlocal at the start of your script. This is the ultimate "Cleanup Routine" for variables; it ensures that all variables created by your script are automatically deleted from memory when the script exits.

Conclusions

Implementing a cleanup routine is a foundational habit for professional scriptwriters. By centralizing your decommissioning logic, deleting temp files, unmapping drives, and resetting the environment, you ensure that your automation remains "Good Citizen" on the user's machine. This attention to detail reduces technical debt and prevents the slow buildup of system junk that can lead to performance issues over time.