在Powershell中压缩按日期过滤的日志文件

时间:2012-01-11 18:06:27

标签: logging scripting powershell zip

\\server\logs下,有一个子目录树,其中包含不遵循一致文件命名约定的归档日志文件。我想运行每日计划任务,将非压缩文件从90天或更早的时间压缩到每日zip文件中。我希望在每个zip中维护目录树结构和文件名。

在Powershell中处理此问题的最佳方式是什么?

编辑:除非有更好的方法,我认为zip文件应该在\\server\oldlogs中创建,并在特定的日期命名,例如。 \\server\oldlogs\20110630_logs.zip。上次修改超过90天的\\server\logs下的所有文件都应添加到相应的.zip文件中。

2 个答案:

答案 0 :(得分:0)

这是66%的解决方案(午餐结束)。我无法使用PowerShell使用本机zip,但如果安装了PowerShell社区扩展,则应该快速更换zip调用 How to create a zip archive with PowerShell?

# purloined from http://blogs.inetium.com/blogs/mhodnick/archive/2006/08/07/295.aspx
# I am not smart enough to make it work. Creates an empty .zip file for me
Function ZipIt
{
    param
    (
        [string]$path
    ,   [string]$files
    )

    if (-not $path.EndsWith('.zip')) {$path += '.zip'} 

    if (-not (test-path $path)) { 
      set-content $path ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) 
    } 

    $zipFile = (new-object -com shell.application).NameSpace($path) 
    #$files | foreach {$zipfile.CopyHere($_.fullname)} 
    foreach($file in $files)
    {
        $zipfile.CopyHere($file)
    }
}

# this script is reponsible for enumerating subfolders
# for each file it finds, it will test the age on it
# returns an array of all the files meeting criteria
Function Walk-SubFolder
{
    param
    (
        [string]$RootFolder
    )

    $searchPattern = "*.*"
    $maxAge = 90
    $now = Get-Date

    # receiver for the files
    [string[]] $agedOutFileList = @()

    foreach($file in [System.IO.Directory]::GetFiles($RootFolder, $searchPattern, [System.IO.SearchOption]::AllDirectories))
    {
        # test whether the file meets the age criteria
        $age = [System.IO.File]::GetLastWriteTime($file)
        $days = ($now - $age).Days
        if (($now - $age).Days -ge $maxAge)
        {
            # this needs to be archived
            Write-Host("$file is aged $days days")
            $agedOutFileList = $agedOutFileList + $file
        }
    }

    return $agedOutFileList
}

Function PurgeFiles
{
    param
    (
        $fileList
    )
    foreach($file in $fileList)
    {
        # this should be in a try/catch block, etc, etc
        [System.IO.File]::Delete($file)
    }
}

$sourceFolder = "C:\tmp\so"
$zipFile = "C:\tmp\so.zip"


$oldFiles = Walk-SubFolder $sourceFolder
ZipIt $zipFile $oldFiles

#This is commented out as the zip process is not working as expected
#PurgeFiles $oldFiles

我会看看以后是否可以使用它来使zip工作正常。

答案 1 :(得分:0)

从.NET 3开始,System.IO.Packaging.ZipPackage可以进行压缩。 <{3}}中没有子文件夹但可以处理this example

日期过滤器可以是这样的:

$ninetyDaysAgo = (get-date).adddays(-90)
$Files | where {$_.lastWriteTime -lt $ninetyDaysAgo}