Powershell脚本中的异常没有意义

时间:2019-12-28 14:35:31

标签: powershell

我们在Windows 2016服务器上有一个SQL Server,该服务器每周{@ 1}和日志文件的SQL Server备份创建,计划每周工作时间为23:30。我创建了客房整理脚本,以开始删除这些早于两个工作日的.MDF文件。

但是,星期二的检查功能异常。在.bak部分下面的脚本中,文件保留为星期一,星期五和星期四,而不是仅星期一和星期五。但是,如果我将其更改为AddDays(4),则仅保留星期一的文件。

为什么会这样?

AddDays(3)

3 个答案:

答案 0 :(得分:0)

为什么完全使用手动缩写而不使用星期几中的int数
(0->星期日,6->星期六)?这将使代码更短,并且您不必担心语言环境的工作日名称。

# Determine day of week
$today   = Get-Date
$weekDay = [int]$today.DayOfWeek   # today's weekday: 0 --> Sunday, 6 --> Saturday

# Write date to log file to ensure sripts ran
Write-output ('{0:ddMMyyyy}' -f $today) | Out-file <path>\HouseKeepLog.txt -append
# If not a sunday or Monday then process
if ($weekDay -gt 1) {
    # use '.Date' to strip off the time part, effectively return the date at midnight
    $refDate = switch ($weekDay) {
        2 { $today.AddDays(-4).Date }        # Tuesday:   delete files greater than 4 days old
        default { $today.AddDays(-2).Date }  # Wed..Sat:  delete files greater than 2 days old
    }
    Get-ChildItem –Path '<Path to backup folder>' -Recurse -Filter '*.bak' -Exclude 'master*', 'msdb*' -File | 
        Where-Object {($_.LastWriteTime -lt $refDate)} | 
        Remove-Item -WhatIf
}

P.S。如果您对控制台中显示的结果感到满意,请删除-WhatIf开关或将其注释掉

答案 1 :(得分:0)

“ Tu”不是“ Tue”?顺便说一句,您可以将枚举与字符串进行比较:

(get-date).dayofweek -eq 'saturday'
True

'saturday' -eq (get-date).dayofweek
True

好,这是星期几枚举的​​布局方式:

(get-date).dayofweek.gettype()               

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     DayOfWeek                                System.Enum

0..6 | foreach { [system.dayofweek]$_ } 

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

答案 2 :(得分:0)

您也可以使用UFormat。方法如下:

$today = Get-Date 
$wd = Get-Date -UFormat "%A"
Write-output ('{0:ddMMyyyy}' -f $today >><path>\HouseKeepLog.txt
if (($wd -notmach "Su.*") -and ($wd -notmatch "Mo.*")) {
   $rd = switch -Regex ($wd) {
     "Tu.*" { $today.AddDays(-4).Date }    
     default { $today.AddDays(-2).Date }
    }
 Get-ChildItem "Path to backup folder" -Recurse -Filter "*.bak" -Exclude "master*", "msdb*" -File | 
            Where-Object {($_.LastWriteTime -lt $rd)} | 
            Remove-Item
}