简体   繁体   中英

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

I have a folder structure containing SQL full and incremental backups, all with the file extention .bak. I want to delete all the incrementals only. All my full backups are created on Sunday, so essentially I want to delete all *.bak files that are created any day other then a Sunday.

How can this be achieved?

PowerShell can be used to filter files based on specific criteria, including filtering by day of the week. The following block can teach you how it can be achieved. Comments are inline.

# 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 = @()

If you're feeling confident you can do this all in one line.

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

Remove the -WhatIf parameter if you're happy with the end result and you want to actually delete the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM