A Windows batch script (delexcept.cmd) that deletes all files in a directory and its subdirectories while preserving files that match specified patterns.
* and ?)delexcept.cmd [TARGET_DIR] [KEEP_FILES]
| Argument | Description | Default |
|---|---|---|
TARGET_DIR |
Directory to process | Current directory (%CD%) |
KEEP_FILES |
Space-separated patterns of files to preserve | *.log *.cfg |
# Delete all files in current directory except *.log and *.cfg
delexcept.cmd
# Process specific directory with default keep patterns
delexcept.cmd "C:\MyFolder"
# Keep only text files in specified directory
delexcept.cmd "C:\Temp" "*.txt"
# Keep multiple file types
delexcept.cmd "D:\Project" "*.log *.cfg *.ini *.txt"
# Mix wildcards with exact filenames
delexcept.cmd "." "important.sql backup.* *.log"
# Use single character wildcards
delexcept.cmd "C:\Data" "config.? log*.txt"
| Pattern | Description | Example Matches |
|---|---|---|
* |
Any number of characters | *.txt → file.txt, document.txt |
? |
Single character | log?.txt → log1.txt, logA.txt |
*.* |
Any file with extension | All files with extensions |
file.* |
Specific name, any extension | file.txt, file.log, file.cfg |
The script displays a warning and requires user confirmation:
WARNING: This will delete all files in "C:\MyFolder" and subdirectories
EXCEPT files matching these patterns: *.log *.cfg
Are you sure? (Y/N):
Display usage information:
delexcept.cmd -h
delexcept.cmd --help
delexcept.cmd /?
delexcept.cmd# Keep source code, remove build artifacts
delexcept.cmd "C:\MyProject" "*.cs *.sql *.js *.html *.css"
# Keep recent logs, remove everything else
delexcept.cmd "C:\Logs" "*.log *.txt"
# Keep specific backup files
delexcept.cmd "D:\Backups" "backup_*.sql important.*"
# Remove temp files but keep configuration
delexcept.cmd "%TEMP%" "*.cfg *.ini *.conf"
⚠️ Warning: This script permanently deletes files. Always test with a backup or in a safe environment first.
"C:\My Folder"* and ? wildcards)"Cannot access directory" error
Files not matching expected patterns
dir command first: dir *.logPermission denied errors
Before running the deletion script, test your patterns:
# Test what files match your pattern
dir /s "*.log"
dir /s "config.*"
This script is provided as-is for educational and practical use. Use at your own risk.