为什么批处理文件使用通配符?不起作用,但 * 起作用

问题描述 投票:0回答:1

在名为 ZipForCloudMaster 的文件夹中,我有一个批处理文件和一个 zip 文件,如下所示:

ZipForCloudAll.bat
ZipForCloudMaster 2025-01-16_08-35-22.zip

批处理文件将文件夹及其内容压缩到一个以文件夹名称和日期时间戳命名的 zip 文件中。然后将 zip 文件上传到云文件夹进行备份。但首先,批处理文件会检查是否存在任何旧的 zip 文件,以警告我,如果继续,我会将旧的 zip 压缩到 zip 中进行上传,这会导致大量膨胀。为此,我使用以下代码:

set "zipMask=ZipForCloudMaster ????-??-??_??-??-??.zip"
for %%A in (%zipMask%) do (
    REM echo %%~xA
    if /I "%%~xA"==".ZIP" (
        if !zcnt!==0 echo Zip files present:
        echo %%A
        set /a zcnt+=1
    )
)

这不起作用,显然发现 0 个带有该 zipMask 签名的 zip 文件。如果我将 zipMask 更改为:

set "zipMask=ZipForCloudMaster *.zip"

它工作得很好,除了它还捕获与包含 ? 的掩码不匹配的其他拉链。通配符。

我做错了什么?

windows batch-file wildcard
1个回答
0
投票

您应该将

dir
/B
标志和
findstr

结合使用
@echo off
setlocal enabledelayedexpansion

set "zipMask=ZipForCloudMaster ????-??-??_??-??-??.zip"
set "zcnt=0"

REM Use dir and pipe through findstr to handle the specific pattern
for /f "delims=" %%A in ('dir /b /a-d ^| findstr /r /i "^ZipForCloudMaster [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]_[0-9][0-9]-[0-9][0-9]-[0-9][0-9]\.zip$"') do (
    if !zcnt!==0 echo Zip files present:
    echo %%A
    set /a zcnt+=1
)

if !zcnt!==0 (
    echo WARNING: Older zip files found. Proceeding will include these in the new zip.
) else (
    echo No older zip files found. Safe to proceed.
)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.