ChatGPT解决这个技术问题 Extra ChatGPT

如何使用 PowerShell 创建 zip 存档?

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


B
Brant Bobby

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 参数。
w
wonea

与 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,看我的回答。
应该读到我需要完整的路径。好纠结的小伙子!顺便说一句,这应该是公认的答案
A
Andrew Diamond

如果您前往 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/…
s
sonjz

采用最新 .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") ;

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

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


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

安装 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 循环可以解决问题& "C:\Program Files\7-Zip\7z.exe" a -tzip ($file.FullName+".zip") $file.FullName
K
Krishna Prasad Yalavarthi

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

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

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

通过压缩 LiteralPath 参数指定的两个文件 Draft doc.docxDiagram [2].vsd 创建新存档文件 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 扩展名附加到文件名。


C
Community

编辑二 - 这段代码是过去的丑陋丑陋的kluge。你不想要。

这将按照示例 here 使用 System.IO.Packaging.ZipPackage 将 .\in 的内容压缩到 .\out.zip

$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 还有一个不再使用它的重要理由!您在这里的“主要问题”竞争激烈;)
s
sirdank

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

需要 .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)

c
chwarr

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

另请参阅 Compress-Archive 的 Microsoft Docs。

示例 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

P
Pluto

为什么没有人看文档?每个人都在引用的同一个 .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该文件):

您可以通过为 CreateEntryFromFile(...) 指定第四个参数来压缩文件。

创建条目会返回一个 ZipArchiveEntry。此对象允许您在之后检查压缩文件,包括让您报告 .CompressedLength、查看或更改 .LastWriteTime(需要更新模式),以及更多下文。

如果您稍后需要检查 ZIP 存档,您可以访问其 .Entries 属性,并使用上述方法以及查看文件名、完整路径、解压缩大小或删除文件(需要更新模式)。

您可以稍后以两种方式提取存档。首先打开它,然后提取整个存档或单个条目(来自 .Entries 或 .GetEntry(...))。您也可以仅通过文件名提取存档。

如果您需要使用流,您可以创建一个空条目并打开其流以供之后写入。您还可以修改现有的 zip 条目(来自 .Entries 或 .GetEntry(...)),这可以让您在内存中完成所有操作。

我鼓励您browse the documentation,因为这就是我发现这一切的方式。


谢谢你,这是完美的。尤其是与 Compress-Archive cmdlet 相比,后者的设计很糟糕并且没有一种好的方法来指定 zip 内部的路径。
e
evandrix

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


C
Community

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

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

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


下面是使用 7 zip 和 Powershell 的 AES 加密的示例:codeblog.theg2.net/2010/02/…
M
Michal Sznajder

这真的很晦涩但有效。 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

}

D
Dherik

如果有人需要压缩单个文件(而不是文件夹):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 对象的另一个答案,因为它没有解决这些陷阱。
A
Arkesh Patel

这是工作代码,压缩源文件夹中的所有文件并在目标文件夹中创建一个 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.."

V
Venkatakrishnan
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:包含您要压缩的文件的目录的完整路径。


R
Roman O

如果您安装了 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:\';
L
Lou O.

这是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)
}

您能否详细说明您的答案,添加更多关于您提供的解决方案的描述?
我采用了先前的答案并通过添加覆盖选项对其进行了改进,无需多说!
C
Community

这也适用于在不使用临时文件夹和使用本机 .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()
        }
    }
}

出色的。我一直在寻找一种方法来压缩 ONE 文件,而无需使用该 shell.application 业务或 7-Zip/其他单独的实用程序。我也喜欢 Using-Object 函数,尽管我采用了一种更短、更快速的方法,没有它。
O
Owen Blacker

我使用此代码段检查我的数据库备份文件夹中尚未压缩的备份文件,使用 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


A
Alex

这是从 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');}"

问候


P
Paul Latour

加载 [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 错误,例如访问已经存在的文件,捕获该错误并将其定向到我正在使用更大程序维护的日志文件。


h
henrycarteruk

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:\梧桐'); }"


u
user3569196

旧线程但仍然,我到了这里:)

这不是原始问题的答案,但也许有人会发现如何使用 PS 创建 ZipArchive 对象很有用。

# Example, if you have like I have a $myByteArray byte[] with the compressed data:
Add-Type -AssemblyName System.IO.Compression.FileSystem

# Fixed length stream:
$strm = New-Object -TypeName System.IO.MemoryStream -ArgumentList @(, $myByteArray);

# Create ZipArchive object
$arch = [System.IO.Compression.ZipArchive]::new($strm);

# List entries
$arch.Entries

已经有一个公认的答案。这个答案并不新鲜,已经有多个基于 System.IO.Compression.ZipFile 的 .NET 答案。