Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 799 Vote(s) - 3.59 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to create a zip archive with PowerShell?

#1
Is it possible to create a zip archive using PowerShell?
Reply

#2
This is really obscure but works. **7za.exe** is standalone version of 7zip and is available with install package.

# 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

}
Reply

#3
<!-- language-all: lang-csharp -->
I use this snippet to check my database backups folder for backup files not compressed yet, compress them using 7-Zip, and finally deleting the `*.bak` files to save some disk space.
Notice files are ordered by length (smallest to biggest) before compression to avoid some files not being compressed.

$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 }

Here you can check a [PowerShell script to backup, compress and transfer those files over FTP][1].


[1]:

[To see links please register here]

Reply

#4
For compression, I would use a library (7-Zip is good like [Michal suggests](

[To see links please register here]

)).

If you install [7-Zip][1], the installed directory will contain `7z.exe` which is a console application.
You can invoke it directly and use any compression option you want.

If you wish to engage with the DLL, that should also be possible.
7-Zip is freeware and open source.


[1]:

[To see links please register here]

Reply

#5
In case you have WinRAR installed:

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;
}


The meaning of the arguments: afzip creates zip archive, df deletes files, ep1 does not create full directory path within archive
Reply

#6
**Edit two** - This code is an ugly, ugly kluge from olden days. You do not want it.

<!-- language-all: lang-csharp -->
This compresses the contents of `.\in` to `.\out.zip` with System.IO.Packaging.ZipPackage following the example [here][1]

$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()

**Edit:** [Unreliable][2] for larger files, maybe >10mb, YMMV. [Something][3] [to do][4] with appdomain evidence and isolated storage. The friendlier .NET 4.5 [approach][5] works nicely from PS v3, but wanted more memory in my case. To use .NET 4 from PS v2, config files need an [unsupported][6] [tweak][7].


[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]

[4]:

[To see links please register here]

[5]:

[To see links please register here]

[6]:

[To see links please register here]

[7]:

[To see links please register here]

Reply

#7
Install 7zip (or download the command line version instead) and use this PowerShell method:

<!-- language-all: lang-csharp -->

function create-7zip([String] $aDirectory, [String] $aZipfile){
[string]$pathToZipExe = "$($Env:ProgramFiles)\7-Zip\7z.exe";
[Array]$arguments = "a", "-tzip", "$aZipfile", "$aDirectory", "-r";
& $pathToZipExe $arguments;
}

You can the call it like this:

create-7zip "c:\temp\myFolder" "c:\temp\myFolder.zip"
Reply

#8
<!-- language-all: lang-csharp -->

PowerShell v5.0 adds [`Compress-Archive`][1] and [`Expand-Archive`][2] cmdlets. The linked pages have full examples, but the gist of it is:

# 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

[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply

#9
If someone needs to zip a single file (and not a folder):

[To see links please register here]


[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
Reply

#10
Here is a slightly improved version of sonjz's answer,it adds an overwrite option.


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)
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through