[英]Keep 10 most recent folders and delete the others
I have this cmd file, where I create a backup of a database我有这个 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
::----------------------------------------------------------------------------------
So What I'm trying to do is creating a script, which only alllows 10 folders to exist, and the 10 folders should always be the latest.所以我要做的是创建一个脚本,它只允许存在 10 个文件夹,并且这 10 个文件夹应该始终是最新的。 So if a 11 backup folder is made, then delete the oldest folder (1), and keep the latest (10)所以如果做了11个备份文件夹,那么删除最旧的文件夹(1),保留最新的(10)
Made a solution that works, where I skip the first 10, and if there is more than that, then we delete.做了一个有效的解决方案,我跳过前 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"
)
This seems more concise in PowerShell.这在 PowerShell 中似乎更简洁。 This is written for a .bat fie script.这是为 .bat fie 脚本编写的。 When you are confident that the correct directories will be deleted, remove the -WhatIf
from the Remove-Item
command.当您确信将删除正确的目录时,请从Remove-Item
命令中Remove-Item
-WhatIf
。
powershell -NoLogo -NoProfile -Command ^
Get-ChildItem -Directory 'C:\backup\*' | Sort-Object -Property LastWriteTime -Descending | Select-Object -Skip 10 | Remove-Item -Recurse -WhatIf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.