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

如何修改批处理命令实现多文件并行处理?

Alright, let's tweak your batch script to run 2-3 parallel process.exe instances and fix a small oversight in your original code. Here's the modified version, plus a breakdown of how it works:

Modified Batch Script

@echo off
setlocal enabledelayedexpansion

:: Set max parallel processes (adjust to 2 or 3 based on your CPU)
set "MAX_PROCS=3"
set "PROCESSED_COUNT=0"

echo Starting parallel processing with up to %MAX_PROCS% concurrent tasks...

FOR %%i in (C:\input\*.*) DO (
    :: Fix: Use %%~nxi to get just the filename/extension (avoids nested path bug)
    set "OUTPUT_PATH=C:\output\%%~nxi"
    
    if not exist "!OUTPUT_PATH!" (
        :: Wait until we have an open slot for a new process
        :WAIT_FOR_SLOT
        for /f %%a in ('tasklist /nh /fi "imagename eq process.exe" ^| find /c /v ""') do set "ACTIVE_PROCS=%%a"
        if !ACTIVE_PROCS! geq !MAX_PROCS! (
            timeout /t 1 /nobreak >nul
            goto WAIT_FOR_SLOT
        )
        
        :: Launch the process in the background (no new window)
        echo Processing: %%i
        start /b "" process.exe "%%i" -out "!OUTPUT_PATH!"
        set /a PROCESSED_COUNT+=1
    )
)

:: Wait for all remaining processes to finish before exiting
:WAIT_FOR_ALL
for /f %%a in ('tasklist /nh /fi "imagename eq process.exe" ^| find /c /v ""') do set "ACTIVE_PROCS=%%a"
if !ACTIVE_PROCS! gtr 0 (
    echo Waiting for !ACTIVE_PROCS! remaining tasks to complete...
    timeout /t 2 /nobreak >nul
    goto WAIT_FOR_ALL
)

echo ---- Finished processing %PROCESSED_COUNT% files ----
pause
endlocal

Key Changes & Explanations

  • Fixed Output Path Bug: Your original script tried to create C:\output\C:\input\filename.ext (since %%i includes the full input path). Using %%~nxi extracts just the filename and extension, so output files go directly into C:\output\.
  • Concurrent Process Control:
    • MAX_PROCS sets the upper limit for parallel tasks (adjust to 2 if 3 uses too much CPU).
    • The :WAIT_FOR_SLOT loop checks how many process.exe instances are running with tasklist. If we hit the max, it waits 1 second and checks again.
  • Background Execution: start /b runs each process.exe in the background without opening a new command window.
  • Wait for All Tasks: The final :WAIT_FOR_ALL loop ensures the script doesn't show "finished" until every last process.exe has completed.
  • Processed Count: Tracks how many files were actually processed (skips those with existing output files).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:46:39