批处理脚本文件编号存在性判断逻辑异常求助
Fixing Your Batch Script's File Check Logic
Let's start by unpacking why your current script is acting up:
- Your
IF EXIST "%FileNumber%"checks are looking for a file named exactly like the number you input (e.g., if you type123, it searches for a file literally called123), not for XML files that contain that number in their filename. That's why even after successfully copying the correct file, it still claims the file doesn't exist.
Here's the corrected script with clear explanations of the changes:
@echo off setlocal :FileNum cls :: Reset the "file found" flag at the start of each input attempt set "FileFound=0" set /P "FileNumber=Please enter File Number: " :: Handle empty input case first if not defined FileNumber ( echo Please enter a valid file number! pause goto :FileNum ) :: Search target directory for XML files matching the input number, copy them, and mark as found for /R "\bpclient\A001\M0093" %%I in ("*%FileNumber%*.xml") do ( copy /Y "%%I" "\IlnevalExtractionTool\Data\" set "FileFound=1" ) :: Use the flag to decide next steps if %FileFound% equ 0 ( echo File Number %FileNumber% Does Not Exist echo Try again pause goto :FileNum ) else ( goto :result ) :result cls :: Combine copied XML files into Results.txt copy Data\*.xml Results.txt endlocal
Key Fixes & Improvements:
- Added a
FileFoundflag variable to track whether any matching XML files were located during the search. This replaces your incorrectEXISTchecks, which were targeting the wrong thing entirely. - Added a safeguard for empty input, so the script doesn't act weird if the user just presses Enter.
- Used
setlocalto contain all script variables to this session—this prevents leftover values from messing with future runs of the script. - The
for /Rloop now setsFileFound=1whenever it finds and copies a matching file, so we can reliably use that flag to determine if the input was valid.
Now, when you enter a number that matches an XML file, the script will copy it and jump straight to the result section. If no matches are found, it'll prompt you to try again.
内容的提问来源于stack exchange,提问作者Ilneval
相关产品推荐
相关产品推荐

