PowerShell로 zip 아카이브를 작성하는 방법
PowerShell을 사용하여 zip 아카이브를 생성할 수 있습니까?
PowerShell v5.0에 cmdlet 추가 및 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 3 및 와 함께 작동하는 순수 PowerShell 대체 제품.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 아카이브의 전체 경로와 압축할 파일이 들어 있는 디렉토리의 전체 경로를 전달하기만 하면 됩니다.
CodePlex로 이동하여 PowerShell Community Extensions를 가져오면 다음과 같은 기능을 사용할 수 있습니다.write-zip
sysloglet.
부터
CodePlex는 셧다운 준비로 읽기 전용 모드입니다.
PowerShell 갤러리로 이동합니다.
최신의 네이티브 방식.기능이 전혀 없는 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") ;
전술한 바와 같이 기능이 전혀 없으므로 덮어쓰기 플래그를 기대하지 마십시오.
업데이트: 수년간 이를 확장해 온 다른 개발자에 대해서는 아래를 참조하십시오.
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"
최초 답변이 게시된 이후 많은 내용이 변경되었습니다.다음은 Compress-Archive 명령을 사용한 최신 예입니다.
파일을 하기 위한 .Draft.zip
2개의 파일, 2개의 파일, 2개의 파일, 2개의 파일을 하는 것으로써Draftdoc.docx
★★★★★★★★★★★★★★★★★」diagram2.vsd
, , , , , 。Path
파라미터를 지정합니다.이 작업에 지정된 압축 수준은 최적입니다.
Compress-Archive -Path C:\Reference\Draftdoc.docx, C:\Reference\Images\diagram2.vsd -CompressionLevel Optimal -DestinationPath C:\Archives\Draft.Zip
파일 「」을 명령어.Draft.zip
2개의 파일, 2개의 파일, 2개의 파일, 2개의 파일을 하는 것으로써Draft doc.docx
★★★★★★★★★★★★★★★★★」Diagram [2].vsd
, , , , , 。LiteralPath
파라미터를 지정합니다.이 작업에 지정된 압축 수준은 최적입니다.
Compress-Archive -LiteralPath 'C:\Reference\Draft Doc.docx', 'C:\Reference\Images\Diagram [2].vsd' -CompressionLevel Optimal -DestinationPath C:\Archives\Draft.Zip
파일을 하기 위한 .Draft.zip
, 의C:\Archives
폴더입니다.새로운 아카이브 파일에는 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
이치노
편집 2 - 이 코드는 옛날부터의 추하고 추한 클루지입니다.당신은 그것을 원하지 않는다.
이렇게 이에의, 의 of this of of this this 、 this this this this 。.\in
로로 합니다..\out.zip
를 사용합니다.IO. 패키징.여기 예시와 같은 Zip Package
$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()
편집: 10MB를 초과하는 대용량 파일에는 신뢰성이 낮습니다.YMMV. AppDomain 증거 및 격리된 스토리지와 관련이 있습니다.더 친근하게.PS v3에서는, NET 4.5 어프로치가 유효하게 기능합니다만, 이 경우는 메모리를 증설하고 싶다고 생각하고 있었습니다.를 사용하려면 ,PS v2의 NET 4 구성 파일에는 지원되지 않는 수정이 필요합니다.
아래에 다른 옵션을 제시합니다.그러면 전체 폴더가 압축되고 지정된 이름의 경로에 아카이브가 기록됩니다.
가 필요합니다.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)
은 cmdlet "Cmdlet" " v5는 과 같습니다.Compress-Archive
PowerShell을 사용하여 Zip 파일을 만듭니다.
「Microsoft Docs for 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 아카이브를 조작하는 방법에 대한 개요입니다(그 후에 파일을 닫으십시오).
- 의 네 번째 파라미터를 지정하여 파일을 압축할 수 있습니다.
- 엔트리를 작성하면가 반환됩니다.이 오브젝트를 사용하면 나중에 zip 파일을 검사할 수 있습니다.예를 들어 보고서 작성, (필요 모드) 표시 또는 변경 등이 가능합니다.
- 나중에 ZIP 아카이브를 검사해야 할 경우 해당 속성에 액세스하고 위의 방법을 사용하여 파일 이름, 전체 경로, 압축 해제 크기 또는 파일 삭제(필요 모드)를 수행할 수 있습니다.
- 아카이브는 나중에 두 가지 방법으로 추출할 수 있습니다.먼저 파일을 열고 아카이브 전체 또는 개별 엔트리를 추출합니다(또는 에서).파일 이름만으로 아카이브를 추출할 수도 있습니다.
- 스트림에 대해 작업해야 하는 경우 빈 엔트리를 만들고 나중에 쓰기 위해 해당 스트림을 열 수 있습니다.기존 zip 엔트리(또는 에서)를 변경하여 메모리 내의 모든 작업을 수행할 수도 있습니다.
이 모든 것을 알게 되었기 때문에 이 문서를 참조해 주셨으면 합니다.
뭐에 대해서?
이 필요합니다.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()
앤더스 헤셀봄 경유
압축에는 라이브러리를 사용합니다(7-Zip이 Michal의 제안대로 좋습니다).
7-Zip을 설치하는 경우 설치된 디렉토리에는 다음 항목이 포함됩니다.7z.exe
콘솔 어플리케이션입니다.
직접 호출하여 원하는 압축 옵션을 사용할 수 있습니다.
DLL을 사용합니다.
및입니다.7-Zip은 프리웨어입니다.
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
}
하나의 파일(폴더가 아닌)을 압축할 필요가 있는 경우: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
다음은 소스 폴더에서 모든 파일을 압축하고 대상 폴더에 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.."
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:지퍼를 올리다
소스 디렉토리:압축할 파일이 들어 있는 디렉토리의 전체 경로입니다.
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은 아카이브 내에 완전한 디렉토리 경로를 생성하지 않습니다.
다음은 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)
}
이것은 temp 폴더를 사용하지 않고 native를 사용하지 않고1개의 파일을 압축하는 경우에도 유효합니다.이 StackOverflow 응답에서 C#에서 변환된 Net 4.5.여기서 가져온 구문을 사용하여 더 좋은 방법을 사용합니다.
사용방법:
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()
}
}
}
되지 않은 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를 통해 파일을 백업, 압축 및 전송할 수 있습니다.
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');}"
안부 전해요
의 [System.IO.IOException]
이 클래스는 PowerShell의 네이티브 클래스가 아니기 때문에 원하지 않는 오류를 억제하기 위한 중요한 단계이므로 이 클래스가 없으면 다양한 오류 컨텍스트를 예상할 수 있습니다.
했지만, 「T」, 「File exists」, 「File exists」를 했을 때에, 많은 의 「 exists했습니다.[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 에러를 검출하는 것입니다.
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:\Indus'); }"
오래된 스레드지만, 여기 도착했어요:)
원래 질문에 대한 답변은 아니지만 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
언급URL : https://stackoverflow.com/questions/1153126/how-to-create-a-zip-archive-with-powershell
'sourcetip' 카테고리의 다른 글
기존 테이블에 기본 키 추가 (0) | 2023.04.08 |
---|---|
클래스 vsVB 모듈그물 (0) | 2023.04.08 |
★★ ★★ ★★떤떤것 ?을 용? ???떤떤것 ?을 용? ???떤떤것 ?을 용? ??? (0) | 2023.04.08 |
SQL에서 시간 없이 날짜를 선택하는 방법 (0) | 2023.04.08 |
CSS를 사용하여 HTML5 입력 자리 표시자 색상 변경 (0) | 2023.04.08 |