0
我有一個包含SQL完全備份和增量備份的文件夾結構,所有文件擴展名爲.bak。我只想刪除所有增量。我所有的完整備份都是在星期天創建的,所以基本上我想刪除除星期天以外的任何一天創建的所有* .bak文件。如何刪除除週一特定日期創建的文件以外的所有文件?
這是如何實現的?
我有一個包含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參數。