如何删除除在一周的特定日期创建的文件之外的所有文件?

How to delete all files except those created on a specific day of the week?

我有一个包含 SQL 完整和增量备份的文件夹结构,所有文件扩展名为 .bak。我只想删除所有增量。我所有的完整备份都是在周日创建的,所以基本上我想删除除周日以外的任何一天创建的所有 *.bak 文件。

如何实现?

PowerShell 可用于根据特定条件过滤文件,包括按星期几过滤。下面的块可以教你如何实现它。评论是内联的。

# Get all files which are NOT folders, where the extention matches your required extention.  Use -Recurse to do this recursively - i.e. all subfolders
$allfiles = Get-ChildItem "G:\SQL Backups" -Recurse | where {!$_.PSIsContainer -and $_.Extension -match ".bak"}

# Filter your file list and select objects which do NOT have the Day Of Week value equal to 0 (Which is a Sunday)
$nonsundayfiles = $allfiles | Where-Object { !$_.CreationTime.DayOfWeek.value__ -eq 0 }

#Iterate through all the non sunday filees and delete each one.  Verbose logging to screen.
$nonsundayfiles | ForEach-Object { 
    Write-Host "The File " $_.FullName "was created on" $_.CreationTime.DayOfWeek "and therefore is being deleted"
    Remove-Item $_.FullName -WhatIf
    }

#Empty variables - useful if in PowerShell ISE
$allfiles = @()
$nonsundayfiles = @()

如果您有信心,您可以在一行中完成所有这些。

Get-ChildItem "G:\SQL Backups" -Recurse | where {!$_.PSIsContainer -and $_.Extension -match ".bak" -and !$_.CreationTime.DayOfWeek.value__ -eq 0} | Remove-Item -WhatIf

如果您对最终结果满意并且想要实际删除文件,请删除 -WhatIf 参数。