用于创建包含 3,000 个文件的目录的 Windows 脚本

用于创建包含 3,000 个文件的目录的 Windows 脚本

我们有一些电子邮件存档,会将所有电子邮件转储到一个目录中。由于服务器的一些性能原因,我想设置一个自动任务,每天运行一次脚本,如果主目录中的文件超过 3,000 个(或任意数量),则创建一个带有日期的新目录并将所有主目录文件移动到其中。我敢肯定有人已经写过类似的东西,所以如果有人能指出它,那就太好了。批处理文件或 Powershell 都可以。

答案1

编写并测试。将以下代码复制到 *.bat 文件中。您需要在代码开头修改电子邮件所在的目录。变量 cBig 已设置为 3000,但您可以根据需要更改它。在底部,移动 *.txt 将必须更改以反映您正在移动的电子邮件的扩展名。一旦您测试完毕并满意,您就可以删除暂停命令……它们只是帮助查看发生了什么。祝你好运!

echo off

REM **navigate to the directory
cd\bat_test

REM **store count of files to file count.txt (/a-d removes folders from count)
dir /b /a-d | find /v /c "::" > count.txt

REM **read count back in to variable (easiest way I knew how to do this)
set /p myvar=<count.txt

REM **set your upper limit (in your case 3000)
set cBig=3000



REM **quick display of the number of files
echo %myvar%

pause


REM **is the number of files larger than our upper limit? If so goto BIG
if '%myvar%' gtr '%cBig%' goto BIG



:SMALL
REM **do nothing
exit


:BIG
REM **create new directory with date and move all files
Set FDate=%Date:~-10,10%
Set Fdate=%FDate:/=-%
MD %FDate%
move *.txt ./%FDate%

pause

答案2

未经测试的 .CMD 脚本。

REM @echo off
setlocal enableextensions enabledelayedexpansion

  rem Print all filenames (excl. folders) in current directory into temporary text-file
  set TMPTXT=%TEMP%\%~n0.%RANDOM%.TMP
  dir /B /A-D  1>%TMPTXT%

  rem Count number of files (lines) in text-file
  set FILECNT=0
  for /F %%i in (%TMPTXT%) do (
    set /A FILECNT=!FILECNT!+1
  )
  echo Number of files in folder: !FILECNT!

  rem Is number of files greater than expected?
  if /I !FILECNT! GTR 2999  call :MoveFiles

  del %TMPTXT%
  goto :EOF

:MoveFiles
  rem Construct a folder-name based on date (remember date changes at midnight)
  rem Since the date value is locale specific, you might want to fiddle with string-replacing.
  set SUBFLDR=%DATE%
  mkdir "%SUBFLDR%"
  if /I !ERRORLEVEL! NEQ 0 (
    echo Failed to create sub-folder '%SUBFLDR%'.
    goto :EOF
  )

  rem Move only those files found in text-file to the new folder.
  for /F %%f in (%TMPTXT%) do (
    move  "%%f"  "%SUBFLDR%\."
    if /I !ERRORLEVEL! NEQ 0  echo Failed to move file '%%f'
  )
  goto :EOF

相关内容