批次腳本將檔案從父資料夾移動到大量指定數量的子資料夾中

批次腳本將檔案從父資料夾移動到大量指定數量的子資料夾中

我需要一個批次檔腳本將所有檔案從單一父資料夾移動到所需數量的子資料夾中,只要每個子資料夾接收批次檔或命令列中指定的最大檔案數量。換句話說,腳本必須將父資料夾中的所有檔案分發到其下面的多個子資料夾中(腳本必須自動建立這些子資料夾),從而將檔案移至多個子資料夾中。X文件(其中“X" 是每個子資料夾將接收的檔案量)。

額外要求:

  1. 子資料夾名稱必須根據以下命名法建立:001、002、003 等。

  2. 必須支援各種檔案名稱的檔案(有空格、特殊字元或非英語重音符號等)。

  3. 必須支援數萬個檔案的移動。

  4. 必須在本機管理員權限下在 Windows 10 Professional 中工作。

例如,假設資料夾「D:\Downloads」中有 2400 個文件,並且您希望將它們分發到每個最多包含 1000 個文件的子資料夾中。運行腳本後,將建立以下結構:

D:\Downloads
       |__001
       |__002
       |__003

在哪裡:

D:\Downloads --> Will have no files inside it anymore
       |__001 --> Will have 1000 files inside it
       |__002 --> Will have 1000 files inside it
       |__003 --> Will have the last 400 files inside it

檔案的順序(哪個檔案進入哪個子資料夾)並不重要,也就是說,移動不需要考慮任何特定標準(例如檔案名稱、大小、檔案類型等)。然而,這方面的任何改進都將受到歡迎(例如,首先將最後建立的檔案移至第一個子資料夾的選項)。

有任何想法嗎?


更新

這是對我有用的解決方案:

@echo off
setlocal enableextensions
setlocal enabledelayedexpansion

if not %3.==. goto syntax
if %2.==. goto syntax
:: Checks if %2 is a number:
SET "var="&for /f "delims=0123456789" %%i in ("%2") do set var=%%i
if defined var (goto syntax) 
if /i %1.==. goto syntax
if /i not exist %1 echo. & echo  The folder %1 does not exist... && echo  Folder paths must be typed between "quotes" if there's any empty space. && echo. && goto end

setlocal enableextensions
setlocal enabledelayedexpansion
:: Maximum amount of files per subfolder:
SET limit=%2
:: Initial counter (everytime counter is 1, a new subfolder is created):
SET n=1
:: Subfolder counter:
SET nf=0
::Retrieves the amount of files in the specified folder:
set count=0
for %%A in (%1%\*.*) do set /a count+=1
echo.
echo  Distributing %count% files in subfolders of up to %2 files...
FOR %%f IN (%1%\*.*) DO (
  :: If counter is 1, create a new subfolder with name starting with "00...":
  IF !n!==1 (
    SET /A nf+=1
    MD %1%\00!nf!
  )
  :: Move files into subfolders with names starting with "00...":
  MOVE /-Y "%%f" %1%\00!nf! > NUL
  :: Reset counter when a subfolder reaches the maximum file limit:
  IF !n!==!limit! (
    SET n=1
  ) ELSE (
    SET /A n+=1
  )
)
SET limit=
SET n=
SET nf=
SET count=
echo  Move finished successfully.
goto end

:syntax
echo.
echo  YOU TYPED: movedown %*
echo  SYNTAX: movedown ["full path"] (between quotes if there's any space) [n] (maximum number of files per subfolder)
echo.
:end
ENDLOCAL

相關內容