无法在批处理命令中使用 forfiles 获取文件名的前 4 个字符

Not able to get first 4 characters of the file name using forfiles in batch command

我正在尝试从 H:\temp 文件夹中查找以 C2319* 开头的特定文件,并删除超过 7 天的其余文件

forfiles /P "H:\Temp\" /M *d6a0f2b4728a /D -7 /C "md /C for %I in (@path) do @if [%~nI]:~0,4==[c2319] del @file /F /A:S"

执行上述命令时出现错误

4==[c2319] was unexpected at this time.

如果我遗漏了什么,有人可以告诉我吗。

  1. 你的命令行有错别字:md 应该是 cmd
  2. "H:\Temp\" 中引号前的反斜杠对引号进行转义,应将其删除
  3. 字符串提取:~0,4(实际上应该是5)只适用于普通变量,因为它需要打开和关闭%!,但既然你'必须将循环变量分配给具有延迟扩展的变量(仅在批处理文件中有效)它在 forfiles /c 命令中不起作用。

这是在列表模式下使用 robocopy 的更快解决方案:

@echo off
setlocal enableDelayedExpansion
set folder=H:\Temp

:: recursively list all *d6a0f2b4728a older than 7 days
for /f "delims=" %%a in ('robocopy /s /njh /njs /ns /nc /ndl /is /l /fp /minage:7 "%folder%" "%folder%" *d6a0f2b4728a') do (

    :: trim spaces
    set file=%%a&set file=!file:%folder%=*!
    for /f "delims=* tokens=2" %%b in ("!file!") do (set file=%folder%%%b&set filename=%%~nb)

    :: delete if not c2319*
    if /i not "!filename:~0,5!"=="c2319" del /F /A:S "!file!"
)
pause