【问题标题】:How to create a zip archive with PowerShell?如何使用 PowerShell 创建 zip 存档?
【发布时间】:2010-11-12 07:02:30
【问题描述】:

是否可以使用 PowerShell 创建 zip 存档?

【问题讨论】:

    标签: powershell zip archive


    【解决方案1】:

    为什么没有人看文档?每个人都在引用同一个 .NET 4.5 库,让您可以做任何您想做的事情,包括创建一个空的 ZIP 并向其中添加单个文件。

    代码示例如下:

    # Load the .NET assembly
    Add-Type -Assembly 'System.IO.Compression'
    Add-Type -Assembly 'System.IO.Compression.FileSystem'
    
    # Must be used for relative file locations with .NET functions instead of Set-Location:
    [System.IO.Directory]::SetCurrentDirectory('.\Desktop')
    
    # Create the zip file and open it:
    $z = [System.IO.Compression.ZipFile]::Open('z.zip', [System.IO.Compression.ZipArchiveMode]::Create)
    
    # Add a compressed file to the zip file:
    [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($z, 't.txt', 't.txt')
    
    # Close the file
    $z.Dispose()
    

    以下是有关如何在使用 zip 存档时对其进行操作的概述(请记住之后close 文件):

    我鼓励你browse the documentation,因为这就是我发现这一切的原因。

    【讨论】:

    • 谢谢你,这是完美的。尤其是与 Compress-Archive cmdlet 相比,后者的设计很糟糕,并且没有指定 zip 内部路径的好方法。
    【解决方案2】:

    自从最初的答案发布以来,很多都发生了变化。以下是一些使用 Compress-Archive 命令的最新示例。

    通过压缩Draftdoc.docxdiagram2.vsd(由Path 参数指定)创建新存档文件Draft.zip 的命令。为此操作指定的压缩级别是 Optimal。

    Compress-Archive -Path C:\Reference\Draftdoc.docx, C:\Reference\Images\diagram2.vsd -CompressionLevel Optimal -DestinationPath C:\Archives\Draft.Zip
    

    通过压缩两个文件Draft doc.docxDiagram [2].vsd(由LiteralPath 参数指定)创建新存档文件Draft.zip 的命令。为此操作指定的压缩级别是 Optimal。

    Compress-Archive -LiteralPath 'C:\Reference\Draft Doc.docx', 'C:\Reference\Images\Diagram [2].vsd'  -CompressionLevel Optimal -DestinationPath C:\Archives\Draft.Zip
    

    C:\Archives 文件夹中创建新存档文件Draft.zip 的命令。新存档文件包含 C:\Reference 文件夹中的每个文件,因为在 Path 参数中使用通配符代替了特定文件名。

    Compress-Archive -Path C:\Reference\* -CompressionLevel Fastest -DestinationPath C:\Archives\Draft
    

    命令从整个文件夹创建存档,C:\Reference

    Compress-Archive -Path C:\Reference -DestinationPath C:\Archives\Draft
    

    PowerShell 会自动将 .zip 扩展名附加到文件名。

    【讨论】:

      【解决方案3】:

      这是 PowerShell v5 的本机解决方案,使用 cmdlet Compress-Archive Creating Zip files using PowerShell

      另请参阅 Microsoft Docs Compress-Archive.

      示例 1:

      Compress-Archive `
          -LiteralPath C:\Reference\Draftdoc.docx, C:\Reference\Images\diagram2.vsd `
          -CompressionLevel Optimal `
          -DestinationPath C:\Archives\Draft.Zip
      

      示例 2:

      Compress-Archive `
          -Path C:\Reference\* `
          -CompressionLevel Fastest `
          -DestinationPath C:\Archives\Draft
      

      示例 3:

      Write-Output $files | Compress-Archive -DestinationPath $outzipfile
      

      【讨论】:

        【解决方案4】:

        Windows中用于压缩和提取目录的完整命令行命令如下:

        • 对于压缩:

          powershell.exe -nologo -noprofile -command "& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::CreateFromDirectory('C:\Indus','C:\Indus.zip'); }"
          
        • 提取:

          powershell.exe -nologo -noprofile -command "& { Add-Type -A 'System.IO.Compression.FileSystem';[IO.Compression.ZipFile]::ExtractToDirectory('C:\Indus.zip','C:\Indus'); }"
          

        【讨论】:

          【解决方案5】:

          采用最新 .NET 4.5 框架的原生方式,但完全没有功能:

          创作:

          Add-Type -Assembly "System.IO.Compression.FileSystem" ;
          [System.IO.Compression.ZipFile]::CreateFromDirectory("c:\your\directory\to\compress", "yourfile.zip") ;
          

          提取:

          Add-Type -Assembly "System.IO.Compression.FileSystem" ;
          [System.IO.Compression.ZipFile]::ExtractToDirectory("yourfile.zip", "c:\your\destination") ;
          

          如上所述,完全没有功能,所以不要指望 overwrite 标志。

          更新:请参阅下文了解多年来对此进行扩展的其他开发人员...

          【讨论】:

          • 为什么要使用无特征方法?
          • 这应该是按发布日期和先例顺序排列的公认答案。至于您更新的评论 - 现在确实有很多方法可以做到这一点。我面临需要这个功能,我在 PowerShell 4 上,我发现的第一件事就是原生方式。这是 2009 年的一个很好的问题。我仍然认为在最初提出问题时可能会有进一步的研究。
          【解决方案6】:

          如果您前往 CodePlex 并获取 PowerShell Community Extensions,您可以使用他们的 write-zip cmdlet。

          自从

          CodePlex 处于只读模式以准备关机

          你可以去PowerShell Gallery

          【讨论】:

          • 是的,它使用 7z 作为其大多数压缩 cmdlet 的核心库。我知道,因为我实现了它;)+1
          • 哈哈干得好,x0n。我在 PSCX 中实现了 feed store 提供程序。实用性稍差,但乐趣无穷。 :)
          • 如果使用7z,是否可以使用密码进行压缩?
          • @SemiDemented write-zip [input file/folder] [output file]
          • Powershell 5 附带一个 Compress-Archive cmdlet,可创建 .zip blogs.technet.microsoft.com/heyscriptingguy/2015/08/13/…
          【解决方案7】:

          与 PowerShell 3 和 .NET 4.5 一起使用的纯 PowerShell 替代方案(如果可以使用的话):

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

          只需传递您要创建的 zip 存档的完整路径以及包含您要压缩的文件的目录的完整路径。

          【讨论】:

          • 这真的需要 Powershell 3.0,还是只需要 .net 4.5?对我来说,实际的 powershell 功能看起来很简单,而不仅仅是 .net 编程。
          • @bwerks 查看“编辑”部分here
          • 我正在寻找一种仅压缩单个大文件的方法,但显然没有这种方法。我必须编写代码来创建一个新目录,将单个文件复制到那里,将该目录压缩为一个新的 zip 文件,然后删除该目录进行清理。
          • @Baodad,看我的回答。
          • 应该读到我需要完整路径。好纠结的小伙子!顺便说一句,这应该是公认的答案
          【解决方案8】:

          System.IO.Packaging.ZipPackage 呢?

          它需要 .NET 3.0 或更高版本。

          #Load some assemblys. (No line break!)
          [System.Reflection.Assembly]::Load("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
          
          #Create a zip file named "MyZipFile.zip". (No line break!)
          $ZipPackage=[System.IO.Packaging.ZipPackage]::Open("C:\MyZipFile.zip",
             [System.IO.FileMode]"OpenOrCreate", [System.IO.FileAccess]"ReadWrite")
          
          #The files I want to add to my archive:
          $files = @("/Penguins.jpg", "/Lighthouse.jpg")
          
          #For each file you want to add, we must extract the bytes
          #and add them to a part of the zip file.
          ForEach ($file In $files)
          {
             $partName=New-Object System.Uri($file, [System.UriKind]"Relative")
             #Create each part. (No line break!)
             $part=$ZipPackage.CreatePart($partName, "",
                [System.IO.Packaging.CompressionOption]"Maximum")
             $bytes=[System.IO.File]::ReadAllBytes($file)
             $stream=$part.GetStream()
             $stream.Write($bytes, 0, $bytes.Length)
             $stream.Close()
          }
          
          #Close the package when we're done.
          $ZipPackage.Close()
          

          通过Anders Hesselbom

          【讨论】:

            【解决方案9】:

            加载[System.IO.IOException] 类并使用其方法是抑制不需要的错误的重要步骤,因为它不是PowerShell 的原生类,因此如果没有它,预计会出现各种错误上下文。

            我错误地将我的脚本控制到 T,但在使用 [System.IO.Compression.ZipFile] 类时得到了很多额外的红色“文件存在”输出

            function zipFiles(
                [Parameter(Position=0, Mandatory=$true]
                [string] $sourceFolder,
                [Parameter(Position=1, Mandatory=$true]
                [string]$zipFileName,
                [Parameter(Position=2, Mandatory=$false]
                [bool]$overwrite)
            
            {   
            Add-Type -Assembly System.IO
            Add-Type -Assembly System.IO.Compression.FileSystem
            
            $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
            
            $directoryTest = (Test-Path $dailyBackupDestFolder)
            $fileTest = (Test-Path $zipFileName)
            
            if ( $directoryTest -eq $false) 
            { 
                New-Item -ItemType Directory -Force -Path $dailyBackupDestFolder 
            }
            
                 if ( $fileTest -eq $true)
                 {
                       if ($overwrite -eq $true ){Remove-Item $zipFileName}
                 }   
            
            
                try
                {
                     [System.IO.Compression.ZipFile]::CreateFromDirectory($sourceFolder,$zipFileName,$compressionLevel)       
            
                }
                catch [System.IO.IOException] 
                {
                   Write-Output ($dateTime + ' | ' + $_.Exception.Message ) | Out-File $logFile -append -force 
                }
            } 
            

            我在这里所做的是捕获这些 IO 错误,例如访问已经存在的文件,捕获该错误并将其定向到我正在使用更大的程序维护的日志文件。

            【讨论】:

              【解决方案10】:

              在下面给出另一个选项。这将压缩一个完整的文件夹并将存档写入具有给定名称的给定路径。

              需要 .NET 3 或更高版本

              Add-Type -assembly "system.io.compression.filesystem"
              
              $source = 'Source path here'    
              $destination = "c:\output\dummy.zip"
              
              If(Test-path $destination) {Remove-item $destination}
              
              [io.compression.zipfile]::CreateFromDirectory($Source, $destination)
              

              【讨论】:

                【解决方案11】:

                这里有一个完整的命令行示例,可以从 cmd.exe 或 ssh 或您想要的启动!

                powershell.exe -nologo -noprofile -command "&{ Add-Type -A 'System.IO.Compression.FileSystem' [System.IO.Compression.ZipFile]::CreateFromDirectory('c:/path/to/source/folder/', 'c:/path/to/output/file.zip');}"
                

                问候

                【讨论】:

                  【解决方案12】:
                  function Zip-File
                      {
                      param (
                      [string]$ZipName,
                      [string]$SourceDirectory 
                  
                      )
                         Add-Type -Assembly System.IO.Compression.FileSystem
                         $Compress = [System.IO.Compression.CompressionLevel]::Optimal
                         [System.IO.Compression.ZipFile]::CreateFromDirectory($SourceDirectory,
                              $ZipName, $Compress, $false)
                      }
                  

                  注意:
                  ZipName:您要创建的 Zip 文件的完整路径。

                  SourceDirectory:包含您要压缩的文件的目录的完整路径。

                  【讨论】:

                    【解决方案13】:

                    这也适用于在不使用临时文件夹和使用本机 .Net 4.5 的情况下压缩单个文件,从 StackOverflow answer 转换为 C#。它使用来自here 的更好的语法。

                    用法:

                    ZipFiles -zipFilename output.zip -sourceFile input.sql -filename name.inside.zip.sql

                    代码:

                    function ZipFiles([string] $zipFilename, [string] $sourceFile, [string] $filename)
                    {
                        $fullSourceFile = (Get-Item -Path "$sourceFile" -Verbose).FullName
                        $fullZipFile = (Get-Item -Path "$zipFilename" -Verbose).FullName
                    
                        Add-Type -AssemblyName System.IO
                        Add-Type -AssemblyName System.IO.Compression
                        Add-Type -AssemblyName System.IO.Compression.FileSystem
                    
                        Using-Object ($fs = New-Object System.IO.FileStream($fullZipFile, [System.IO.FileMode]::Create)) {
                             Using-Object ($arch = New-Object System.IO.Compression.ZipArchive($fs, [System.IO.Compression.ZipArchiveMode]::Create)) {
                                 [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($arch, $fullSourceFile, $filename)
                            }
                        }
                    }
                    

                    使用:

                    function Using-Object
                    {
                        [CmdletBinding()]
                        param (
                            [Parameter(Mandatory = $true)]
                            [AllowEmptyString()]
                            [AllowEmptyCollection()]
                            [AllowNull()]
                            [Object]
                            $InputObject,
                    
                            [Parameter(Mandatory = $true)]
                            [scriptblock]
                            $ScriptBlock
                        )
                    
                        try
                        {
                            . $ScriptBlock
                        }
                        finally
                        {
                            if ($null -ne $InputObject -and $InputObject -is [System.IDisposable])
                            {
                                $InputObject.Dispose()
                            }
                        }
                    }
                    

                    【讨论】:

                    • 优秀。我正在寻找一种方法来压缩一个文件,而不使用 shell.application 业务或 7-Zip /其他单独的实用程序。我也喜欢 Using-Object 函数,尽管我选择了一种更短、更快速的方法。
                    【解决方案14】:

                    这是工作代码,压缩源文件夹中的所有文件并在目标文件夹中创建一个 zip 文件。

                        $DestZip="C:\Destination\"
                        $Source = "C:\Source\"
                    
                        $folder = Get-Item -Path $Source
                    
                        $ZipTimestamp = Get-Date -format yyyyMMdd-HHmmss;
                        $ZipFileName  = $DestZip + "Backup_" + $folder.name + "_" + $ZipTimestamp + ".zip" 
                    
                        $Source
                    
                        set-content $ZipFileName ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) 
                        # Wait for the zip file to be created.
                        while (!(Test-Path -PathType leaf -Path $ZipFileName))
                        {    
                            Start-Sleep -Milliseconds 20
                        } 
                        $ZipFile = (new-object -com shell.application).NameSpace($ZipFileName)
                    
                        Write-Output (">> Waiting Compression : " + $ZipFileName)       
                    
                        #BACKUP - COPY
                        $ZipFile.CopyHere($Source) 
                    
                        $ZipFileName
                        # ARCHIVE
                    
                        Read-Host "Please Enter.."
                    

                    【讨论】:

                      【解决方案15】:

                      这是对sonjz的回答稍有改进的版本,它增加了一个覆盖选项。

                      function Zip-Files(
                              [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$false)]
                              [string] $zipfilename,
                              [Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$false)]
                              [string] $sourcedir,
                              [Parameter(Position=2, Mandatory=$false, ValueFromPipeline=$false)]
                              [bool] $overwrite)
                      
                      {
                         Add-Type -Assembly System.IO.Compression.FileSystem
                         $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
                      
                          if ($overwrite -eq $true )
                          {
                              if (Test-Path $zipfilename)
                              {
                                  Remove-Item $zipfilename
                              }
                          }
                      
                          [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir, $zipfilename, $compressionLevel, $false)
                      }
                      

                      【讨论】:

                      • 能否请您详细说明您的答案,添加更多关于您提供的解决方案的描述?
                      • 我拿了一个之前的答案,并通过添加覆盖选项对其进行了改进,不多说了!
                      【解决方案16】:

                      如果有人需要压缩单个文件(而不是文件夹):http://blogs.msdn.com/b/jerrydixon/archive/2014/08/08/zipping-a-single-file-with-powershell.aspx

                      [CmdletBinding()]
                      Param(
                           [Parameter(Mandatory=$True)]
                           [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
                           [string]$sourceFile,
                      
                           [Parameter(Mandatory=$True)]
                           [ValidateScript({-not(Test-Path -Path $_ -PathType Leaf)})]
                           [string]$destinationFile
                      ) 
                      
                      <#
                           .SYNOPSIS
                           Creates a ZIP file that contains the specified innput file.
                      
                           .EXAMPLE
                           FileZipper -sourceFile c:\test\inputfile.txt 
                                      -destinationFile c:\test\outputFile.zip
                      #> 
                      
                      function New-Zip
                      {
                           param([string]$zipfilename)
                           set-content $zipfilename 
                                ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
                           (dir $zipfilename).IsReadOnly = $false
                      }
                      
                      function Add-Zip
                      {
                           param([string]$zipfilename) 
                      
                           if(-not (test-path($zipfilename)))
                           {
                                set-content $zipfilename 
                                     ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
                                (dir $zipfilename).IsReadOnly = $false    
                      
                           }
                      
                           $shellApplication = new-object -com shell.application
                           $zipPackage = $shellApplication.NameSpace($zipfilename)
                      
                      
                           foreach($file in $input) 
                           { 
                                $zipPackage.CopyHere($file.FullName)
                                Start-sleep -milliseconds 500
                           }
                      }
                      
                      dir $sourceFile | Add-Zip $destinationFile
                      

                      【讨论】:

                      • 这段代码依赖于一个 shell 应用程序,然后猜测 500 毫秒等待它完成......我并不反对它的工作原理(在大多数情况下)。但它会在您使用它时创建弹出窗口,其中添加压缩文件需要一些时间(通过添加大文件或使用大 zip 很容易复制)。此外,如果任何 zip 操作比指定的睡眠时间慢,它将无法添加文件并留下一个弹出对话框。这对于脚本来说是可怕的。我还否决了依赖 COM 对象的另一个答案,因为它没有解决这些陷阱。
                      【解决方案17】:

                      PowerShell v5.0 添加了Compress-ArchiveExpand-Archive cmdlet。链接页面有完整的例子,但它的要点是:

                      # Create a zip file with the contents of C:\Stuff\
                      Compress-Archive -Path C:\Stuff -DestinationPath archive.zip
                      
                      # Add more files to the zip file
                      # (Existing files in the zip file with the same name are replaced)
                      Compress-Archive -Path C:\OtherStuff\*.txt -Update -DestinationPath archive.zip
                      
                      # Extract the zip file to C:\Destination\
                      Expand-Archive -Path archive.zip -DestinationPath C:\Destination
                      

                      【讨论】:

                      • PowerShell v5.0 现已正式发布。它还附带 Windows 10。
                      • 来自Compress-Archive 的第 2 段描述:“...您可以使用 Compress-Archive 压缩的最大文件大小当前为 2 GB。这是底层 API 的限制”但是,如果你使用System.IO.Compression.ZipFile你可以绕过这个限制。
                      • 2GB 限制继承自 System.IO.Compression.ZipFile。如果您使用的 .NET 框架没有此限制,则 CmdLet 不应达到此限制。我在代码中验证了。
                      • @Pramod 没有-OutputPath 参数。
                      【解决方案18】:

                      安装 7zip(或下载命令行版本)并使用此 PowerShell 方法:

                      function create-7zip([String] $aDirectory, [String] $aZipfile){
                          [string]$pathToZipExe = "$($Env:ProgramFiles)\7-Zip\7z.exe";
                          [Array]$arguments = "a", "-tzip", "$aZipfile", "$aDirectory", "-r";
                          & $pathToZipExe $arguments;
                      }
                      

                      你可以这样称呼它:

                      create-7zip "c:\temp\myFolder" "c:\temp\myFolder.zip"
                      

                      【讨论】:

                      • 如果 7zip 在您的路径中,那么您只需要编写 "& 7z c:\temp\myFolder c:\temp\myFolder.zip"
                      • 如果不想安装,可以下载命令行版本代替。 (只需查看 7-zip 的下载页面。)它只是一个可执行文件,命令语法相同。但是,可执行文件的名称不同;出于某种原因,它是 7za.exe。我在许多项目中都这样做过,从未失望过。
                      • 我尝试使用 .net 和 Powershell 工具的时间太长了,直到使用 7zip 路径,该路径立即起作用。 $file 上的简单 foreach 循环可以解决问题&amp; "C:\Program Files\7-Zip\7z.exe" a -tzip ($file.FullName+".zip") $file.FullName
                      【解决方案19】:

                      编辑两个 - 这段代码是过去的丑陋丑陋的组合。你不想要它。

                      这会将.\in 的内容压缩为.\out.zip 与 System.IO.Packaging.ZipPackage 遵循示例here

                      $zipArchive = $pwd.path + "\out.zip"
                      [System.Reflection.Assembly]::Load("WindowsBase,Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
                      $ZipPackage=[System.IO.Packaging.ZipPackage]::Open($zipArchive,
                        [System.IO.FileMode]"OpenOrCreate", [System.IO.FileAccess]"ReadWrite")
                      $in = gci .\in | select -expand fullName
                      [array]$files = $in -replace "C:","" -replace "\\","/"
                      ForEach ($file In $files)
                      {
                         $partName=New-Object System.Uri($file, [System.UriKind]"Relative")
                         $part=$ZipPackage.CreatePart($partName, "application/zip",
                            [System.IO.Packaging.CompressionOption]"Maximum")
                         $bytes=[System.IO.File]::ReadAllBytes($file)
                         $stream=$part.GetStream()
                         $stream.Write($bytes, 0, $bytes.Length)
                         $stream.Close()
                      }
                      $ZipPackage.Close()
                      

                      编辑: Unreliable 对于较大的文件,可能 >10mb,YMMV。 Something to do 带有 appdomain 证据和隔离存储。更友好的 .NET 4.5 approach 在 PS v3 上运行良好,但在我的情况下需要更多内存。要使用 PS v2 中的 .NET 4,配置文件需要 unsupported tweak

                      【讨论】:

                      • ZipPackage的主要问题是它不是普通的ZIP文件,而是包含一个内容xml文件。请参阅:[如何避免 .net 的 ZipPackage 类中的 [Content_Types].xml - 堆栈溢出](stackoverflow.com/questions/3748970/…)
                      • @aaron 不再使用它的另一个重要理由!您在这里的“主要问题”竞争激烈;)
                      【解决方案20】:

                      如果您安装了 WinRAR:

                      function ZipUsingRar([String] $directory, [String] $zipFileName)
                      {
                        Write-Output "Performing operation ""Zip File"" on Target ""Item: $directory Destination:"
                        Write-Output ($zipFileName + """")
                        $pathToWinRar = "c:\Program Files\WinRAR\WinRar.exe";
                        [Array]$arguments = "a", "-afzip", "-df", "-ep1", "$zipFileName", "$directory";
                        & $pathToWinRar $arguments;
                      }
                      

                      参数含义:afzip 创建 zip 压缩包,df 删除文件,ep1 不创建压缩包内的完整目录路径

                      【讨论】:

                      • 当我看到这个时,我以为我终于找到了我的问题的答案,但是无论我做什么,WinRar都不会运行。如果我使用批处理文件来运行它,一切都很好,但如果我尝试从 PowerShell 脚本运行该批处理文件,则什么也没有发生,它只是继续执行脚本的下一部分,将文件上传到 FTP 服务器。
                      • 我尝试按原样使用此功能,但它什么也没做。我不明白。我的 $Arguments:[Array]$arguments = 'a', '-ag-YYYY-MM-DD-NN', '-dh', '-ed', '-ep3', '-ilogE:\Logs\WinRar\backup.log', '-INUL', '-r', '-y', 'E:\UsageWebLogs\Weblogs', 'W:\', 'X:\', 'Y:\', 'Z:\';
                      【解决方案21】:

                      对于压缩,我会使用一个库(7-Zip 就像 Michal suggests 一样好)。

                      如果您安装7-Zip,安装目录将包含7z.exe,这是一个控制台应用程序。
                      您可以直接调用它并使用您想要的任何压缩选项。

                      如果您希望使用 DLL,也应该可以。
                      7-Zip 是免费软件和开源软件。

                      【讨论】:

                      【解决方案22】:

                      我使用这个 sn-p 检查我的数据库备份文件夹中尚未压缩的备份文件,使用 7-Zip 压缩它们,最后删除 *.bak 文件以节省一些磁盘空间。 注意文件在压缩前按长度(从小到大)排序,以避免某些文件没有被压缩。

                      $bkdir = "E:\BackupsPWS"
                      $7Zip = 'C:\"Program Files"\7-Zip\7z.exe'
                      
                      get-childitem -path $bkdir | Sort-Object length |
                      where
                      {
                          $_.extension -match ".(bak)" -and
                          -not (test-path ($_.fullname -replace "(bak)", "7z"))
                      } |
                      foreach
                      {
                          $zipfilename = ($_.fullname -replace "bak", "7z")
                          Invoke-Expression "$7Zip a $zipfilename $($_.FullName)"
                      }
                      get-childitem -path $bkdir |
                      where {
                          $_.extension -match ".(bak)" -and
                         (test-path ($_.fullname -replace "(bak)", "7z"))
                      } |
                      foreach { del $_.fullname }
                      

                      您可以在这里查看PowerShell script to backup, compress and transfer those files over FTP

                      【讨论】:

                        【解决方案23】:

                        这真的很晦涩,但很有效。 7za.exe 是 7zip 的独立版本,可通过安装包获得。

                        # get files to be send
                        $logFiles = Get-ChildItem C:\Logging\*.* -Include *.log | where {$_.Name -match $yesterday} 
                        
                        foreach ($logFile in $logFiles)
                        {
                            Write-Host ("Processing " + $logFile.FullName)
                        
                            # compress file
                            & ./7za.exe a -mmt=off ($logFile.FullName + ".7z") $logFile.FullName
                        
                        }
                        

                        【讨论】:

                          猜你喜欢
                          • 1970-01-01
                          • 2010-09-18
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 2010-12-23
                          • 1970-01-01
                          相关资源
                          最近更新 更多