每月清理日志的 Powershell 脚本

Powershell Script to clean up logs on a Monthly Basis

Powershell 新手又来问了。

我们目前有一个日志文件夹,用于存储文本文件。我的主管希望我创建一个脚本,其中只有当月的日志可见。之前的所有月份都应移至存档文件夹。他想让我创建一个 powershell 脚本,我们可以每月 运行 一次来实现这一目标。

例如,我们的日志文件夹应该只包含 2021 年 1 月的日志。任何早于 2021 年 1 月的日志都应该存档。一旦 2021 年 2 月 1 日命中,2021 年 1 月的所有日志应移至存档文件夹,依此类推。

我怎样才能实现一个查看文件夹并只保留当月日志的脚本?非常感谢任何指导、资源、视频等!我一直在网上搜索资源,但我还没有找到适合我需要的东西。

更新: 能够在这里找到精彩的脚本:PowerShell: Sort and Move Files by Date to month and year 由 Thomas Maurer 提供(所有功劳都归功于他!)

# Get the files which should be moved, without folders
$files = Get-ChildItem 'C:\Users\testuser\Desktop\log' -Recurse | where {!$_.PsIsContainer}
 
# List Files which will be moved
$files
 
# Target Filder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = 'C:\Users\testuser\Desktop\log\archive'
 
foreach ($file in $files)
{
# Get year and Month of the file
# I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString()
 
# Out FileName, year and month
$file.Name
$year
$month
 
# Set Directory Path
$Directory = $targetPath + "\" + $year + "\" + $month
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}
 
# Move File to new location
$file | Move-Item -Destination $Directory
}

我现在想要实现的目标:这个脚本效果很好,但我正在尝试修改它以便我可以移动除当前月份之外的所有内容。我仍在研究和调查中,所以如果我能够为我弄清楚这个缺失的部分,我将确保更新我的 post。谢谢大家的帮助!

保留本月最后修改的文件的一种方法是使用一个小的辅助函数,将 LastWriteTime 日期格式化为字符串 yyyy\MM

function Format-YearMonth ([datetime]$date) {
    # simply output a string like "2021"
    return '{0:yyyy\MM}' -f $date
}

$sourcePath = 'C:\Users\testuser\Desktop\log'
$targetPath = 'C:\Users\testuser\Desktop\log\archive'
$thisMonth  = Format-YearMonth (Get-Date)

# Get the files which should be moved, without folders 
# this can be more efficient if all files have the same extension on which
# you can use -Filter '*.log' for instance.
Get-ChildItem -Path $sourcePath -File -Recurse | 
    # filter out the files that have a LastWriteTime for this year and month
    Where-Object {(Format-YearMonth $_.LastWriteTime) -ne $thisMonth } |
    ForEach-Object {
        # Set destination Path
        $Directory = Join-Path -Path $targetPath -ChildPath (Format-YearMonth $_.LastWriteTime)
        # Create directory if it doesn't exsist
        if (!(Test-Path $Directory)) {
            $null = New-Item $Directory -type Directory
        }
        Write-Host "Moving file '$($_.FullName)' to '$Directory'"
        # Move File to new location
        $_ | Move-Item -Destination $Directory -Force
    }