powershell脚本从每月的第一天开始删除文件,而不是保留它们

时间:2019-05-03 17:21:04

标签: powershell

{ name = "Joe"; age = 12}

这应从30天内开始保存文件,并保留剩余的所有文件。目前,它正在删除每月的1号并保留其余的时间。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您的逻辑使我感到困惑[ blush ],因此我改用日期计数而不是日期时间比较来重写它。

$SourceDir = $env:TEMP

$Today = (Get-Date).Date
$YearInDays = 365
$MonthInDays = 30

#Clean-Up Old Backup Files
Get-ChildItem -LiteralPath $SourceDir -File |
    ForEach-Object {
        $DaysOld = ($Today - $_.LastWriteTime).Days
        if ($DaysOld -gt $YearInDays)
            {
            ''
            'LWT = {0}' -f $_.LastWriteTime
            'File age in days = {0}' -f $DaysOld
            Write-Host "I want to remove files older than a year"

            Remove-Item $_.FullName -WhatIf
            }
            Elseif ($DaysOld -gt $MonthInDays -and
                $_.LastWriteTime.Day -ne 1)
            {
            ''
            'LWT = {0}' -f $_.LastWriteTime
            'File age in days = {0}' -f $DaysOld
            Write-Host "I want to remove files older than 1 month, but not the first of the month"

            Remove-Item $_.FullName -WhatIf
            }
            Else
            {
            ''
            'LWT = {0}' -f $_.LastWriteTime
            'File age in days = {0}' -f $DaysOld
            Write-Host 'Nothing to remove'
            }
    }

输出...

LWT = 2015-11-03 6:54:02 PM
File age in days = 1276
I want to remove files older than a year
What if: Performing the operation "Remove File" on target "C:\Temp\FXSAPIDebugLogFile.txt".

LWT = 2019-03-04 12:45:30 PM
File age in days = 59
I want to remove files older than 1 month, but not the first of the month
What if: Performing the operation "Remove File" on target "C:\Temp\Itunes_Default-Rating_Set.ps1_2019-05-03.log".

LWT = 2019-03-01 12:44:23 PM
File age in days = 62
Nothing to remove

LWT = 2015-11-03 9:35:03 PM
File age in days = 1276
I want to remove files older than a year
What if: Performing the operation "Remove File" on target "C:\Temp\qtsingleapp-fmlast-93b-1-lockfile".

LWT = 2019-05-03 6:43:11 AM
File age in days = 0
Nothing to remove