如何使用PowerShell创建zip存档?

Val*_*yev 234 powershell zip

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

pet*_*snd 253

适用于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)
}
Run Code Online (Sandbox Code Playgroud)

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


Bra*_*bby 225

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

# 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
Run Code Online (Sandbox Code Playgroud)

  • PowerShell v5.0现已正式发布.它还附带Windows 10. (11认同)
  • 来自“ Compress-Archive”的第2段说明:“ ...当前可以使用Compress-Archive压缩的最大文件大小为2 GB。这是底层API的补充”,但是,如果您使用`System.IO .Compression.ZipFile`,您可以绕过此限制。 (2认同)
  • 2GB 限制继承自“System.IO.Compression.ZipFile”。如果您使用的 .NET 框架没有此限制,则 CmdLet 不应达到此限制。我在代码中进行了验证。 (2认同)
  • @Pramod没有`-OutputPath`参数。 (2认同)

Mat*_*ton 120

如果您前往CodePlex并获取PowerShell社区扩展,则可以使用其write-zipcmdlet.

以来

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

你可以去PowerShell Gallery.

  • 是的,它使用7z作为其大多数压缩cmdlet的核心库.我知道,因为我实施了它;)+1 (110认同)
  • Powershell 5附带了一个Compress-Archive cmdlet,用于创建.zip https://blogs.technet.microsoft.com/heyscriptingguy/2015/08/13/new-feature-in-powershell-5-compress-files/ (7认同)
  • @SemiDemented `write-zip [输入文件/文件夹] [输出文件]` (3认同)
  • 使用代码片段演示会很好;) (2认同)

son*_*njz 57

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

创建:

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

萃取:

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

如上所述,完全没有功能,所以不要指望覆盖标志.

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


Kar*_*non 44

安装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;
}
Run Code Online (Sandbox Code Playgroud)

你可以这样称呼它:

create-7zip "c:\temp\myFolder" "c:\temp\myFolder.zip"
Run Code Online (Sandbox Code Playgroud)

  • 如果7zip在你的路径中,那么你需要写的是"&7z c:\ temp\myFolder c:\ temp\myFolder.zip" (6认同)
  • 如果您不想安装它,可以下载命令行版本.(只需查看7-zip的下载页面.)它只是一个可执行文件,命令语法是相同的.但是,可执行文件的名称不同; 它出于某种原因是7za.exe.我在很多项目上做过这件事,从未失望过. (5认同)

noa*_*oam 15

编辑二 - 这段代码是古代丑陋丑陋的代码.你不想要.

这将压缩的内容.\in,以.\out.zip与System.IO.Packaging.ZipPackage下面的例子在这里

$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()
Run Code Online (Sandbox Code Playgroud)

编辑: 对于较大的文件不可靠,可能> 10mb,YMMV.东西 与应用程序域证据和独立存储.友好的.NET 4.5 方法在PS v3中运行良好,但在我的情况下需要更多的内存.要从PS v2使用.NET 4,配置文件需要不受支持的 调整.


小智 12

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

需要.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)
Run Code Online (Sandbox Code Playgroud)


nik*_*nik 7

对于压缩,我会使用一个库(7-Zip就像Michal建议的那样好).

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

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

  • 以下是使用Powershell的AES加密7 zip的示例:http://codeblog.theg2.net/2010/02/powershell-7-zip-amazon-s3-upload.html (2认同)

aar*_*ron 7

以下是PowerShell v5的本机解决方案,使用Compress-Archive 使用PowerShell创建Zip文件的cmdlet .

另请参阅Microsoft Docs for Compress-Archive.

例1:

Compress-Archive `
    -LiteralPath C:\Reference\Draftdoc.docx, C:\Reference\Images\diagram2.vsd `
    -CompressionLevel Optimal `
    -DestinationPath C:\Archives\Draft.Zip
Run Code Online (Sandbox Code Playgroud)

例2:

Compress-Archive `
    -Path C:\Reference\* `
    -CompressionLevel Fastest `
    -DestinationPath C:\Archives\Draft
Run Code Online (Sandbox Code Playgroud)

例3:

Write-Output $files | Compress-Archive -DestinationPath $outzipfile
Run Code Online (Sandbox Code Playgroud)


Pet*_* P. 6

怎么样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()
Run Code Online (Sandbox Code Playgroud)

通过Anders Hesselbom


Plu*_*uto 6

为什么没人看文档?每个人都引用的同一个 .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()
Run Code Online (Sandbox Code Playgroud)

这是有关如何在使用 zip 存档时操作它的概述(请记住之后关闭文件):

我鼓励您浏览文档,因为这就是我发现所有这些的方式。

  • 谢谢你,这太完美了。特别是与 Compress-Archive cmdlet 相比,该 cmdlet 设计很糟糕,并且没有很好的方法来指定 zip 内部的路径。 (2认同)

Kri*_*thi 5

自发布初始答案以来,批次已更改。以下是一些使用Compress-Archive命令的最新示例。

命令来创建新的存档文件,Draft.zip通过压缩两个文件,Draftdoc.docx并且diagram2.vsd,由指定的Path参数。为此操作指定的压缩级别为“最佳”。

Compress-Archive -Path C:\Reference\Draftdoc.docx, C:\Reference\Images\diagram2.vsd -CompressionLevel Optimal -DestinationPath C:\Archives\Draft.Zip
Run Code Online (Sandbox Code Playgroud)

命令来创建新的存档文件,Draft.zip通过压缩两个文件,Draft doc.docx并且Diagram [2].vsd,由指定的LiteralPath参数。为此操作指定的压缩级别为“最佳”。

Compress-Archive -LiteralPath 'C:\Reference\Draft Doc.docx', 'C:\Reference\Images\Diagram [2].vsd'  -CompressionLevel Optimal -DestinationPath C:\Archives\Draft.Zip
Run Code Online (Sandbox Code Playgroud)

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

Compress-Archive -Path C:\Reference\* -CompressionLevel Fastest -DestinationPath C:\Archives\Draft
Run Code Online (Sandbox Code Playgroud)

Command从整个文件夹创建档案, C:\Reference

Compress-Archive -Path C:\Reference -DestinationPath C:\Archives\Draft
Run Code Online (Sandbox Code Playgroud)

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