我們有一些電子郵件存檔,將所有電子郵件轉儲到一個目錄中。由於伺服器的一些效能原因,我想設定一個自動化任務,每天執行一次腳本,如果主目錄中有超過 3,000 個(或任何數量)的文件,則建立一個包含日期的新目錄並將所有主目錄檔案移入其中。我確信有人已經寫過類似的東西,所以如果有人能指出我的話那就太好了。批次檔或 Powershell 都可以。
答案1
已編寫並經過測試。將以下程式碼複製到 *.bat 檔案中。您需要在程式碼開頭修改電子郵件所在的目錄。變數 cBig 已設定為 3000,但您可以根據需要變更此設定。必須更改底部的 move *.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