简体   繁体   中英

Remove files from .zip file with Powershell

I am going to write a Powershell script to remove files from a .zip file. In my .zip file, I have test.txt (latest) test1.txt (older) test2.txt .... testN.txt (oldest), all with different file sizes (or in powershell, it's called Length). I want to keep only 2G or smaller of them and remove the rest. It is required to remove from the oldest ones. Since the .zip file may be very large. It's better not to extract it and zip again.

Is there any way to achieve this?

Thank you so much.

Adopting this VBScript solution :

$zipfile = 'C:\path\to\your.zip'
$files   = 'some.file', 'other.file', ...
$dst     = 'C:\some\folder'

$app = New-Object -COM 'Shell.Application'
$app.NameSpace($zipfile).Items() | ? { $files -contains $_.Name } | % {
  $app.Namespace($dst).MoveHere($_)
  Remove-Item (Join-Path $dst $_.Name)
}

If you have .net Framework 4.5 installed, something like this should work, too:

[Reflection.Assembly]::LoadWithPartialName('System.IO.Compression')

$zipfile = 'C:\path\to\your.zip'
$files   = 'some.file', 'other.file', ...

$stream = New-Object IO.FileStream($zipfile, [IO.FileMode]::Open)
$mode   = [IO.Compression.ZipArchiveMode]::Update
$zip    = New-Object IO.Compression.ZipArchive($stream, $mode)

($zip.Entries | ? { $files -contains $_.Name }) | % { $_.Delete() }

$zip.Dispose()
$stream.Close()
$stream.Dispose()

The parentheses around filtering items from the Entries collection are required, because otherwise the subsequent Delete() would modify the collection. This would prevent reading (and thus deleting) other items from the collection. The resulting error message looks like this:

An error occurred while enumerating through a collection: Collection was modified;
enumeration operation may not execute..
At line:1 char:1
+ $zip.Entries | ? { $filesToRemove -contains $_.Name } | % { $_.Delete() }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Collecti...ipArchiveEntry]:Enumerator) [], RuntimeException
    + FullyQualifiedErrorId : BadEnumeration

Use 7-Zip , a free Zip tool. A Technet sample illustrates how to create a zip archive with 7-Zip in Powershell.

Learn the proper commands to get a listing of your zip's contents and use the d command to delete files from within the archive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM