如何在批处理(.bat)脚本运行时按文件名忽略文件删除?
Hey there! Let's sort out that batch script problem you're facing. The command you tried (del Tasks\^*Project\*.xml) doesn't work because batch's wildcard system doesn't support excluding patterns directly like that. Here are two solid solutions to get what you need:
Method 1: Using a for loop (simple and easy to tweak)
This approach loops through every XML file in the Tasks folder, checks if the filename doesn't contain "Project", and deletes it if that's the case.
@echo off setlocal enabledelayedexpansion for %%f in (Tasks\*.xml) do ( :: Extract the filename without extension or path set "filename=%%~nf" :: Check if removing "Project" from the filename changes it (meaning "Project" was present) if not "!filename!"=="!filename:Project=!" ( del "%%f" ) ) endlocal
Quick breakdown:
@echo offhides the commands being executed, making the output cleanersetlocal enabledelayedexpansionlets us read updated variables inside the loop (critical for this logic)%%~nfgrabs just the filename (no extension, no folder path) from the full file path!filename:Project=!replaces any "Project" text in the filename with nothing. If the result is different from the original filename, that means "Project" was present—so we skip deleting that file.
Method 2: Using robocopy (faster for lots of files)
Robocopy is a powerful built-in Windows tool for file operations. We can use it to temporarily move the files we want to keep, delete the rest, then move the kept files back.
@echo off :: Create a temporary folder to hold files we want to keep mkdir Tasks\temp :: Move all XML files with "Project" in the name to the temp folder robocopy Tasks Tasks\temp *Project*.xml /MOV :: Delete all remaining XML files in Tasks del Tasks\*.xml :: Move the kept files back from temp to Tasks robocopy Tasks\temp Tasks *.xml /MOV :: Clean up the temporary folder rmdir Tasks\temp
Quick breakdown:
/MOVtells robocopy to move files (delete them from the source after copying) instead of just copying- The temporary folder ensures we don't accidentally delete the files we want to keep
- This method is much faster if you have a large number of XML files in the Tasks folder
Pro tip for testing:
Before running the script for real, replace del "%%f" (in Method 1) or del Tasks\*.xml (in Method 2) with echo del "%%f" or echo del Tasks\*.xml. This will print out which files would be deleted without actually removing them—great for verifying the logic works as expected!
内容的提问来源于stack exchange,提问作者Carthic

