Batch Script Cleanup Exclusions Guide
A guide for safely excluding specific folders from cleanup routines in Windows batch scripts.
Batch Script Cleanup Exclusions Guide
Overview
This document explains how to safely exclude specific folders (such as
Backgrounds) from cleanup routines in Windows batch scripts. It is
designed as a reusable reference for administrators.
Problem
Standard cleanup functions like:
Call :RemoveSubfoldersAndFiles <path>
remove everything inside a directory, making it impossible to exclude specific subfolders directly.
Solution Approach
Instead of calling the cleanup function on the root folder, loop through subfolders and exclude specific ones.
Core Pattern
for /d %%i in ("<path>\*") do if /i not "%%~nxi"=="<EXCLUDE_FOLDER>" call :RemoveSubfoldersAndFiles "%%i"
Explanation
for /d %%i in (...)→ loops through directories only\%%~nxi→ extracts folder name\if /i not→ case-insensitive exclusion\call :RemoveSubfoldersAndFiles→ executes existing cleanup logic
Example (Microsoft Teams Cache)
for /d %%i in ("%UserProfilePath%\AppData\local\Packages\MSTeams_8wekyb3d8bbwe\LocalCache\Microsoft\MSTeams\*") do if /i not "%%~nxi"=="Backgrounds" call :RemoveSubfoldersAndFiles "%%i"
Result
Folder Action
------------- ---------
Backgrounds Kept
Cache Deleted
GPUCache DeletedReusable Template
set TARGET=<path>
set EXCLUDE=<folder>
for /d %%i in ("%TARGET%\*") do if /i not "%%~nxi"=="%EXCLUDE%" call :RemoveSubfoldersAndFiles "%%i"
Multiple Exclusions
for /d %%i in ("%TARGET%\*") do (
if /i not "%%~nxi"=="Backgrounds" if /i not "%%~nxi"=="ImportantFolder" call :RemoveSubfoldersAndFiles "%%i"
)Best Practices
1. Never delete root blindly
Always avoid running cleanup directly on folders containing user data.
2. Use exclusions for user-generated content
Examples: - Teams backgrounds - Browser profiles - Custom configs
3. Test with echo (dry-run)
for /d %%i in ("%TARGET%\*") do if /i not "%%~nxi"=="Backgrounds" echo Would clean %%i
4. Keep scripts maintainable
Prefer readable loops over overly compact one-liners in production environments.
Integration Strategy
You can apply this pattern in: - Temp cleanup scripts - Log rotation scripts - Cache cleanup routines - Enterprise login scripts (GPO)
Summary
- Direct cleanup removes everything → unsafe\
- Loop-based cleanup → flexible and safe\
- Exclusion logic → essential for modern environments
This pattern ensures safe automation while preserving critical user data.
Installing Microsoft Office via Winget with Custom XML Configuration
A guide on how to use Winget to install Microsoft Office while maintaining control over installation settings through an existing Office Deployment Tool (ODT) configuration XML file.
PowerShell Dry-Running
Learn how to safely test your PowerShell scripts using dry-run techniques to prevent unintended consequences.