【发布时间】:2019-12-28 14:35:31
【问题描述】:
我们在 Windows 2016 服务器上有一个 SQL Server,它会创建 .MDF 的 SQL Server 备份,并在工作日的 23:30 安排一次日志文件。我创建了一个管家脚本来开始删除这些超过两个工作日的.bak 文件。
但是,星期二的检查功能异常。在下面的脚本中,AddDays(4) 部分保留了周一、周五和周四的文件,而不仅仅是周一和周五。但如果我将其更改为AddDays(3),它只会保留星期一的文件。
为什么会这样?
# 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(),因此您可能包含了脚本运行的时间,从而导致了意外的输出。尝试将调试信息添加到您的脚本中,以找出发生逻辑错误的位置。
标签: powershell