Compress a folder using powershell

时间:2023-03-09 09:28:49
Compress a folder using powershell

There are many ways to compress a folder using powershell:

Method 1: Using System.IO.Compression and System.IO.Compression.FileSystem

Add-Type -AssemblyName System.IO.Compression
Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::CreateFromDirectory($source_WebPortal, $destination_WebPortal,[System.IO.Compression.CompressionLevel]::Fastest,$True)

This method requires .NET Framework 4.5 installed

参考链接:https://gist.github.com/stefanteixeira/0428e8ade6be09d94b90

Method 2: Using pure Powershell script

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 200
}
} dir $tempFolder\*.* -Recurse | add-Zip $zipFile

This method can be run at powershell 2.0 and .NET Framework 4.0

参考链接:https://blogs.msdn.microsoft.com/daiken/2007/02/12/compress-files-with-windows-powershell-then-package-a-windows-vista-sidebar-gadget/

Method 3: Using PowerShell Community Extensions

1) Download the extension from http://pscx.codeplex.com/

2) Unzip and put the folder in $PSHome\Modules

3) Execute cmdlet import-module pscx

4) Use the cmdlet write-zip to compress file

This method requires administator permission

参考链接:http://*.com/questions/1153126/how-to-create-a-zip-archive-with-powershell