We have some email archiving that is dumping all the emails into a directory. Because of some performance reasons with the server, I want to setup an automated task that will run a script once a day and if there is more than 3,000 (or whatever number) of files in the main directory, create a new directory with the date and move all the main directory files into it. I'm sure someone has already written something similar, so if anyone could point me at it that would be great. Batch file or Powershell would both be fine.
Written and tested. Copy the following code into a *.bat file. You'll want to modify the directory where the emails exist at the start of the code. The variable cBig has already been set to 3000 but you can change this if you'd like. At the bottom, move *.txt will have to be changed to reflect the extension of the emails you're moving. Once you've tested it and are happy you can remove the pause commands... they just help see what's going on. Good luck!
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
Untested .CMD script.
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