用于每月清理日志的 Powershell 脚本

问题描述

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
}

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

解决方法

一种方法以留下上次在这个月修改的文件是用一个小的辅助函数格式LastWriteTime日期成字符串yyyy\MM

function Format-YearMonth ([datetime]$date) {
    # simply output a string like "2021\01"
    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
    }