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


当前回答

为什么没人看文档?每个人都引用的. 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存档的概述(只是记得之后关闭文件):

You can compress files by specifying a fourth parameter for CreateEntryFromFile(...). Creating an entry returns a ZipArchiveEntry. This object lets you inspect the zipped file afterwards including letting you report the .CompressedLength, view or change the .LastWriteTime (needs Update mode), and more below. If you need to inspect the ZIP archive later, you can access its .Entries property, and use the methods above as well as view the filename, the full path, the decompressed size, or delete the file (needs Update mode). You can extract an archive two ways later. First open it, then extract either the entire archive or an individual entry (from .Entries or .GetEntry(...)). You can also extract an archive by its filename alone. If you need to work with streams, you can create an empty entry and open its stream for writing afterwards. You can also modify an existing zip entry (from .Entries or .GetEntry(...)), which would let you do everything in-memory.

我鼓励您浏览文档,因为这是我找到所有这些的方法。

其他回答

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

要求。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)

我使用这个代码段检查数据库备份文件夹中尚未压缩的备份文件,使用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脚本通过FTP备份、压缩和传输这些文件。

对于压缩,我会使用库(如Michal所建议的,7-Zip很好)。

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

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

下面是PowerShell v5的原生解决方案,使用cmdlet压缩-归档使用PowerShell创建Zip文件。

请参见微软文档 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

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

}