我的问题有点复杂。让我详细说明一下:
我现在有一个批处理文件,它将创建4个文件夹 - 它们是:
1
2
3
4
这4个文件夹中的每个文件夹中都有2个文件。我想要做的是创建一个批处理文件,该文件将保留这4个文件夹中最小的文件夹并删除其他文件夹。因此,如果文件夹大小如下:
1 = 300,000 b
2 = 325,000 b
3 = 250,000 b
4 = 350,000 b
然后只保留文件夹3,并删除文件夹1,2和4。
这可以用批处理文件完成吗?任何帮助将不胜感激。
感谢。
答案 0 :(得分:1)
@echo off
setlocal enableextensions enabledelayedexpansion
rem Configure where to start
set "root=%cd%"
rem Initialize needed variables
set "minSize=99999999999999999999"
set "minFolder="
set "size="
set "folder="
for %%a in ("%root%") do set "drive=%%~da"
rem Retrieve the full list and from it get only the lines that
rem contain the folder name and the file count/size
for /f "skip=2 delims=" %%z in ('
dir /-c /s /a-d "%root%\*" ^| findstr /r /c:"^ [ ]*[0-9]" /c:":\\.*"
') do (
rem Determine if the current line is a folder name, or folder statistics.
rem If we have already read a folder name, the next record should be the sizes
rem else we have a folder name or the final statistics for the dir command
if defined folder (
rem Read the size and format as a zero prefixed string to avoid 2^31 limit
rem in batch files arithmetic. All the size tests will be a string test.
for /f "tokens=3" %%a in ("%%z") do set "size=00000000000000000000%%a" & set "size=!size:~-20!"
) else (
rem Read the folder name and reset the size for this folder. As the colon is used
rem to separate the folder name from the rest of the data in the line, the drive
rem letter and colon are removed. Append the initially retrieved one.
for /f "tokens=2 delims=:" %%a in ("%%z") do set "folder=%drive%%%a"
set "size="
)
rem When a size is available, a folder has also being retrieved.
rem As we have all the needed information, check if the current folder size
rem is less than the previous minimal folder and delete the previous or the
rem current one depending on its size
if defined size (
if "!size!" lss "!minSize!" (
rem Old folder is bigger, remove it and remember current folder info
if defined minFolder echo rd /s /q "!minFolder!"
set "minSize=!size!"
set "minFolder=!folder!"
) else (
rem Current folder is bigger, remove it
echo rd /s /q "!folder!"
)
rem In any case, the current folder has been processed. Initialize variables
set "size="
set "folder="
)
)
很多代码,但我试图只执行一个dir
命令来检索所有需要的信息。
根据需要更改root
变量。此外,所有rd
命令仅回显到控制台。如果输出正确,请删除echo
操作前面的rd
命令。
答案 1 :(得分:0)
将此批处理文件放在包含4个数据文件夹的文件夹中,然后运行它:
@echo off
setlocal EnableDelayedExpansion
rem Get size of all folders
set smallestSize=9999999999
for /D %%a in (*) do (
set size=0
for %%b in (%%a\*.*) do set /A size+=%%~Zb
if !size! lss !smallestSize! (
set smallestSize=!size!
set smallestName=%%a
)
)
echo Folder to keep: "%smallestName%"
pause
rem Delete all folders, excepting the smallest one
for /D %%a in (*) do (
if "%%a" neq "%smallestName%" rd /S /Q "%%a"
)