是否可以使用PowerShell创建zip存档?
当前回答
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:包含要压缩的文件的目录的完整路径。
其他回答
一个纯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归档文件的完整路径,以及包含您想要压缩的文件的目录的完整路径。
如果有人需要压缩单个文件(而不是一个文件夹):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
下面是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.
我鼓励您浏览文档,因为这是我找到所有这些的方法。
加载[System.IO.]类,并使用它的方法是抑制不必要错误的重要步骤,因为它不是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错误,例如访问已经存在的文件,捕获该错误并将其指向我正在使用更大的程序维护的日志文件。
推荐文章
- 如何在PowerShell中获得MD5校验和
- 如何在PowerShell格式化日期时间
- PowerShell和-contains操作符
- 使用PowerShell删除超过15天的文件
- 数组添加 vs +=
- 致命错误:类“ZipArchive”未在
- Mac压缩没有__MACOSX文件夹?
- PowerShell中用户输入的提示符
- 如何从字符串执行任意本机命令?
- 如何使用。net 4运行时运行PowerShell ?
- 使用System.IO.Compression在内存中创建ZIP存档
- 在PowerShell中重新加载路径
- 函数在PowerShell中的返回值
- 如何在PowerShell中输出一些东西
- iOS如何设置应用程序图标和启动图像