2009-07-20 86 views

回答

105

如果您转到CodePlex并获取PowerShell Community Extensions,则可以使用它们的write-zip cmdlet。

由于

CodePlex上是只读的准备模式关机

你可以去PowerShell Gallary

+92

是的,它使用7Z为核心库的大多数压缩的cmdlet我知道,我becaues实现它。)+1 – x0n 2009-07-21 01:10:34

+1

笑不错的工作,x0n。我imlpemented在PSCX饲料存储提供稍微不太实用,但吨乐趣:) – 2009-07-21 02:37:23

+1

如果它使用7Z,是否有可能使用密码压缩 – mack 2013-04-17 20:20:27

3

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

} 
6

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

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

如果你想使用DLL,那也应该是可以的。
7-Zip是免费和开源的。

+2

下面是使用Powershell的AES加密使用7 zip的示例:http ://codeblog.theg2.net/2010/02/powershell-7-zip-amazon-s3-upload.html – 2010-02-19 23:22:44

4

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, "application/zip", 
     [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

+2

10有完整源代码的任何示例? – Kiquenet 2012-06-08 08:25:13

37

安装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" 
+6

如果7zip的是在您的路径,那么所有你需要写的是“&7z格式C:\ TEMP \ MyFolder文件C:\ TEMP \ myFolder.zip” – aboy021 2013-06-24 02:17:34

1

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

11

编辑两个 - 这段代码是一个丑陋,丑陋的克鲁日从古代的日子。你不想要。

使用System.IO.Packaging将.\in的内容压缩为.\out.zip。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,情况因人而异。 Somethingto do与appdomain证据和孤立的存储。友好的.NET 4.5 approach从PS v3很好地工作,但在我的情况下需要更多的内存。要使用PS v2中的.NET 4,配置文件需要一个unsupportedtweak

223

纯PowerShell的替代方案,使用PowerShell 3和.NET 4.5(如果你可以使用它)的工作原理:

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档案,你想创建和包含要压缩的文件的目录的完整路径。

45

与最新的.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") ; 

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

1

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

148

PowerShell v5.0增加了Compress-ArchiveExpand-Archive cmdlets。该链接的网页有充分的例子,但它的要点是:

# 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 
3

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

这里有一个稍微改进版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) 
} 
9

给予低于另一个选项。这将压缩完整的文件夹,并将档案写入给定名称的给定路径。

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

下面是工作代码,从源文件夹压缩和解所有文件,并创建在目标文件夹的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.." 
1

这也应该适用于压缩单个文件,而无需使用临时文件夹,并使用原生的.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() 
     } 
    } 
} 
3
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) 
    } 

注:
ZipNa我:你想创建的Zip文件的完整路径。

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

2

这里有一个完整的命令行示例,可以从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');}" 

问候

-3

该脚本遍历所有的目录和zip每一个

GET-ChildItem -attributes开发|的foreach {写-ZIP $ 请将.Name“$($请将.Name)的.zip”}

1

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

0

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

  • 压缩:

powershell.exe -nologo -noprofile -command“& {添加类型-A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile] :: CreateFromDirectory('C:\ Indus', 'C:\ Indus。压缩'); } “

  • 提取:

powershell.exe -nologo -noprofile -command” & {添加型-A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile] :: ExtractToDirectory('C:\ Indus.zip', 'C:\ Indus'); ?}”