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


当前回答

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

其他回答

下面是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

为什么没人看文档?每个人都引用的. 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.

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

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

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

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

如果你安装了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不创建归档内的完整目录路径

如果有人需要压缩单个文件(而不是一个文件夹):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