繁体   English   中英

powershell删除某些超过90天的文件,例外

[英]powershell delete some files older than 90 days, with exceptions

$timeLimit1 = Get-Date.AddDays(-90)
Get-ChildItem <path> | ? {$_.LastWriteTime -le $timeLimit1 } | Remove-Item

所以我有较简单的部分,但是我试图弄清楚如何做一些更复杂的事情。

我正在设置备份删除例程。 要求是保留最后90天的备份,然后保留本年度每个月的最后一天,最后保留前2年12月31日的备份。

除了单笔支票外,我找不到其他示例。 是否有可能做一些检查以使其自动化。

我建议编写一个自定义过滤器以应用逻辑,例如

filter MyCustomFilter{

    $File = $_

    $FileDate = $File.LastWriteTime
    $Now = (Get-Date)
    $FileAgeDays = ($Now - $FileDate).TotalDays

    if (

        # Keep files for at least 90 days
        ( $FileAgeDays -lt 91 
        ) -or

        # Keep files from last day of the month this year
        (  $FileDate.Year -eq $Now.Year -and
           $FileDate.Month -ne $FileDate.AddDays(1).Month
        ) -or

        # Keep files from 31 Dec for up to 2 years
        (   $FileAgeDays -lt ( 2 * 365 ) -and
            $FileDate.Month -eq 12 -and 
            $FileDate.Day -eq 31
        )

    ) { 

        # File should be kept, so nothing is returned by the filter

    } else { 

        # File should be deleted, so pass the file down the pipeline
        write-output $File

    }


}

现在,您的总体代码将如下所示:

get-childItem -path <path> |
    where-object { -not $_.PSIsContainer } |
    MyCustomFilter |
    Remove-Item

毋庸置疑,在生产系统上进行松动之前需要进行适当的测试。

编辑:一个月的最后一天的简单测试

我想测试,这是简单的比较:“每月最后一天”了一个更简洁的month测试日期的财产,用month的次日例如财产

$FileDate.Month -ne $FileDate.AddDays(1).Month

如果$FileDate是该月的最后一天,则将返回$true

只需创建一个包含“特殊”日期的数组并将其添加到过滤器中即可。

$timeLimit1 = Get-Date
$timeLimit1.AddDays(-90)
$specialDates = (Get-Date "31-12-2014"), (Get-Date "31-05-2017") # continue the list 
Get-ChildItem <path> | ? {$_.LastWriteTime -le $timeLimit1 -and $specialDates -notcontains $_.LastAccessTime.Date } | Remove-Item 

我还将创建一个查找“特殊”日期的函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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