2

如何在 PowerShell 中使用 System.IO.Compression.FileSystem将日志文件移动到 zip 存档?

每个应用程序都有更多包含日志文件的文件夹:

app1logfolder
|-app1_20130507.log
|-app1_20130508.log
|-app1_20130509.log

app2logfolder
|-app2_20130507.log
|-app2_20130508.log
|-app2_20130509.log

等等..我想每天将这些文件处理成一个 zip 存档。

logs_20130507.zip
|-app1_20130507.log
|-app2_20130507.log

logs_20130508.zip
|-app1_20130508.log
|-app2_20130508.log

logs_20130509.zip
|-app1_20130509.log
|-app2_20130509.log
4

2 回答 2

3

您可以围绕这样的内容构建一个脚本,该脚本将获取一个文件夹并将其内容放入压缩的 zip 文件中。

$srcdir = "C:\folderYouWantZipped"
$zipFilename = "nameZipfile.zip"
$zipFilepath = "C:\ZipfileLoaction\"
$zipFile = "$zipFilepath$zipFilename"

#Prepare zip file
if(-not (test-path($zipFile))) {
    set-content $zipFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
    (dir $zipFile).IsReadOnly = $false  
}

$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipFile)
$files = Get-ChildItem -Path $srcdir | where{! $_.PSIsContainer}

foreach($file in $files) { 
    $zipPackage.CopyHere($file.FullName)
#using this method, sometimes files can be 'skipped'
#this 'while' loop checks each file is added before moving to the next
    while($zipPackage.Items().Item($file.name) -eq $null){
        Start-sleep -seconds 1
    }
}

更多有帮助的链接:

于 2013-05-09T13:53:17.787 回答
0

您可以使用以下代码。只需将以下代码粘贴到.ps1文件中并调用ZipFiles函数ZipFiles $sourceFolderPath $zipFileName

    function ZipFiles($sourcedir, $zipfilename)
    {
       if ($zipfilename -notMatch ".zip")
       {
            $zipfilename = $zipfilename + ".zip"
       }       
       $onelevelup=Split-Path -Path $sourcedir -Parent
       $zipfilename = $onelevelup + "\" + $zipFileName

       Add-Type -Assembly System.IO.Compression.FileSystem
       $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
       [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir, $zipfilename, $compressionLevel, $false)

       CopyFile $zipfilename $sourcedir
    }

    function CopyFile( $copySource, $destinationSource)
    {
      Copy-Item $copySource $destinationSource -Recurse
    }
于 2017-07-11T13:08:49.357 回答