PowerShell:使用System.IO.Compression.FileSystem将文件移动到zip

时间:2013-05-09 09:38:24

标签: .net logging powershell compression zip

如何使用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

2 个答案:

答案 0 :(得分:2)

你可以围绕这样的东西构建一个脚本,它将获取一个文件夹并将其内容放入压缩的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
    }
}

更多有关mite帮助的链接:

答案 1 :(得分: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
    }