保留 10 个最近的文件夹并删除其他文件夹

Keep 10 most recent folders and delete the others

我有这个 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)

制定了一个有效的解决方案,我跳过了前 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"
)

这在 PowerShell 中似乎更简洁。这是为 .bat fie 脚本编写的。当您确信将删除正确的目录时,从 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