我有這個 cmd 檔案,我在其中創建了資料庫的備份
@echo off
Title Get FileName With Date and Time
Call :GetFileNameWithDateTime MyCurrentDate
echo %MyCurrentDate%
cd backups
MkDir %MyCurrentDate%
cd ..
cd bin
mysqldump.exe -u -p --single-transaction --routines --triggers --host test.com --databases database1 > "../backups/%MyCurrentDate%/testBackup.sql"
pause & exit
::----------------------------------------------------------------------------------
:GetFileNameWithDateTime <FileName>
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set "MyDate=%%x"
set "%1=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%-%MyDate:~8,2%-%MyDate:~10,2%"
Exit /B
::----------------------------------------------------------------------------------
所以我要做的是創建一個腳本,它只允許存在 10 個檔案夾,并且這 10 個檔案夾應該始終是最新的。所以如果做了11個備份檔案夾,那么洗掉最舊的檔案夾(1),保留最新的(10)

uj5u.com熱心網友回復:
做了一個有效的解決方案,我跳過前 10 個,如果有更多,那么我們洗掉。
set "delMsg="
for /f "skip=10 delims=" %%a in (
'dir "backups\*" /t:c /a:d /o:-d /b'
) do (
if not defined delMsg (
set delMsg=1
echo More than 10 found - only the 10 most recent folders will be preserved.
)
rd /s /q "backups\%%a"
)
uj5u.com熱心網友回復:
這在 PowerShell 中似乎更簡潔。這是為 .bat fie 腳本撰寫的。當您確信將洗掉正確的目錄時,請-WhatIf從Remove-Item命令中洗掉。
powershell -NoLogo -NoProfile -Command ^
Get-ChildItem -Directory 'C:\backup\*' | Sort-Object -Property LastWriteTime -Descending | Select-Object -Skip 10 | Remove-Item -Recurse -WhatIf
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/344596.html
