windows 7 中的批处理文件以查找与模式不匹配的文件

Batch file in windows 7 to find files not matching pattern

希望你能帮助我。我需要写一个小的批处理文件,可以放在用户的电脑上(不是一个非常懂计算机的人)来检查一个文件夹(从服务器共享)并列出这个文件夹中与文件模式不匹配的文件。我有一个每晚 运行s 的应用程序,但文件必须命名为 *_*_*.* 如果不是这种格式,应用程序将失败,即使应用程序会给出一些指示,说明哪个文件是不正确,他们浪费了一天,如果他们再错了……改天。他们需要能够 运行 这个简单的批处理文件,它可以只在屏幕上显示错误命名的文件。

我开始阅读有关 forFiles 函数的内容,但一直无法弄清楚如何正确使用它。另外,我可以直接引用这个共享文件夹吗?现在如果我们访问它,它看起来像这样:\dhpServer1\PeopleFolder。这里是应该检查的文件。

非常感谢

您可以生成完整的文件列表并过滤掉那些不符合所需模式的文件。

dir /b /a-d "\dhpServer1\PeopleFolder\*" | findstr /v /r /c:"^[^_][^_]*_[^_][^_]*_.*"

findstr 将过滤 dir 命令的输出,显示不匹配 (/v) 正则表达式 (/r) 指示的行 ( /c:) :

^     at the start of the line
[^_]  a non underscore character
[^_]* followed by zero or more non underscore characters
_     followed by an underscore
[^_]  followed by a non underscore character
[^_]* followed by zero or more non underscore characters
_     followed by an underscore
.*    followed by any sequence of zero or more characters

可能是表达方式需要调整。这个表达式只是我对你写的*_*_*.*的解释(当然我可能是错的),但与[=中通配符的行为不匹配13=] 命令。 "^[^_]*_[^_]*_.*" 更接近于指示的通配符表达式的行为。

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir\t w o"
SET "errorfound="
FOR /f "delims=" %%a IN (
  'dir /b /a-d "%sourcedir%\*" '
  ) DO (
 SET "error="
 FOR /f "tokens=1-3*delims=_" %%p IN ("q%%a") DO (
  IF "%%p" equ "q" SET error=Y
  IF "%%s" neq ""  SET error=Y
  IF "%%r" equ ""  SET error=Y
  IF NOT DEFINED error (
   FOR /f "tokens=1,2*delims=." %%x IN ("q%%r") DO (
    IF "%%x" equ "q" SET error=Y
    IF "%%y" equ ""  SET error=Y
    IF "%%z" neq ""  SET error=Y
   )
  )
  IF DEFINED error (
   ECHO %%a is invalid FORMAT
   SET errorfound=y
  ) ELSE (ECHO %%a is OK)
 )
)
IF DEFINED errorfound (
 ECHO error found
 PAUSE
) ELSE (
 ECHO All OK!
 timeout /t 5 >nul
)
GOTO :EOF

您需要更改 sourcedir 的设置以适合您的情况。

这是一个示例输出:

a_valid_file.name is OK
_invalid_file.namestartingunderscore is invalid FORMAT
an_invalid_file_name.toomanyundescores is invalid FORMAT
invalid_file.nameinsufficientunderscores is invalid FORMAT
an_invalid_.filenameterminalunderscoreinname is invalid FORMAT
an_extra_invalid_.filenameterminalunderscoreinname is invalid FORMAT
an_invalid_filenamewithnoextension is invalid FORMAT
an_invalid_filenamewith.multiple.extensions is invalid FORMAT
error found
Press any key to continue . . . 

如果所有文件的格式均有效,程序应显示一条适当的消息 5 秒并终止。

的原理是在使用_.作为分隔符时,通过tokenising来评估名称的各个部分,并利用if defined的特性来切换是否发生错误逐个实例。