You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复批处理代码中的if-else语句以实现PDF处理需求

修复批处理脚本的if-else逻辑与语法错误

问题根源

  1. for循环未闭合:添加if-else后,遗漏了闭合for循环的),导致脚本语法解析失败,直接触发闪退。
  2. echo语句覆盖不全:仅在else分支保留了成功提示,未覆盖if分支的处理场景。
  3. 冗余路径硬编码:已定义pdftk变量但未复用,代码维护性差。

修复后完整代码

@echo off
setlocal enabledelayedexpansion

set "pdftk=C:\Program Files (x86)\PDFtk\bin\pdftk.exe"

set "sourcemap=C:\GIS\Maps\Ranch Map Staging Folders\PCA\Central"
set "sourcetables=C:\GIS\Maps\Ranch Map Staging Folders\PCA\Photos"
set "destination=C:\GIS\Maps\Ranch Map Staging Folders\PCA\Central Completed"

set pdffile=
set pdfattach=
for /f "delims=" %%i in ('dir /b /a-d /o:n "%sourcemap%\*.pdf"') do (
    set "pdffile=%sourcemap%\%%i"
    set "pdfattach=%sourcetables%\PestManagement_TableSeries_!pdffile:~50!"
    set "outputpdf=%%~ni"
    set "outputname=!pdffile:~50,-4! - Field Scout Survey Map %date:~-4,4%%date:~-10,2%%date:~-7,2%.pdf"
    
    if exist "!pdfattach!" (
        "!pdftk!" "!pdffile!" "!pdfattach!" cat output "%destination%\!outputname!"
    ) else (
        move "!pdffile!" "%destination%\!outputname!"
    )
    echo "Successfully completed !pdffile:~50,-4!"
)

set "gisfolder=C:\GIS\Maps\Ranch Map Staging Folders\PCA\Central Completed"
set "spfolder=\\sunpacific.local\lerdodata\Sun Pacific Public\6 - Business Units\Sun Pacific Farming Cooperative\B - General\10 - Maps\Ranch Maps\Other Maps\PCA\Maps\Central"
set "archivefolder=\\sunpacific.local\lerdodata\Sun Pacific Public\6 - Business Units\Sun Pacific Farming Cooperative\B - General\10 - Maps\Other Maps\PCA\Old Maps\Central"

move "%spfolder%\*.pdf" "%archivefolder%"

move "%gisfolder%\*.pdf" "%spfolder%"

cmd /k

关键修复说明

  • 补充for循环闭合的),修复核心语法错误;
  • 将echo语句移至if-else外部,确保无论是否找到附件PDF,都能输出处理成功提示;
  • 复用!pdftk!变量替代硬编码路径,提升代码可维护性;
  • 新增outputname变量统一管理输出文件名,避免重复拼接字符串。

内容的提问来源于stack exchange,提问作者George Bunkall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 12:34:53