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

など..そして、これらのファイルを 1 日ごとに 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 に答える