We have a SQL Server on a Windows 2016 server that creates a SQL Server backup of the .MDF and Log files once a weekday basis scheduled for 23:30. I created a housekeeping script to start deleting these .bak files that are older than two working days.
However, the check for a Tuesday, functions with an anomaly. In the script below the part AddDays(4) retains files for Monday, Friday AND Thursday instead of Monday and Friday only. But if I change this to AddDays(3) it ONLY retains Monday's files.
Why is this behaving like this?
# Determine day of week
$weekDay = (get-date).DayOfWeek.ToString()
$firstAbbrevCheck = $weekDay.SubString(0,3)
# write-host $firstAbbrevCheck
# Write date to log file to ensure sripts ran
$todaysDate = (get-date).ToString("ddMMyyyy")
Write-output $todaysDate | Out-file <path>\HouseKeepLog.txt -append
# If not a sunday or Monday then process
if($firstAbbrevCheck -ne "Sun") {
if($firstAbbrevCheck -ne "Mon") {
$secondAbbrevCheck = $weekDay.SubString(0,2)
# If retaining two work days of backups then for Tuesday delete
files greater than 4 days old
if($secondAbbrevCheck -eq "Tu") {
Get-ChildItem –Path <Path to backup folder> -recurse -Filter
*.bak -exclude master*, msdb* | Where-Object
{($_.LastWriteTime -lt (Get-Date).AddDays(-4))} | Remove-Item
}
else {
# Else Wed - Sat and delete files greater than 2 days old
Get-ChildItem –Path <Path to backup folder> -recurse -Filter
*.bak -exclude master*, msdb* | Where-Object
{($_.LastWriteTime -lt (Get-Date).AddDays(-2))} | Remove-Item
}
}
}
(get-date).adddays(), you are including the TIME the script runs at and thus leading to unexpected output. Try and add debugging information to your script to find out where the logical error occurs.