简体   繁体   English

使用Powershell从.zip文件中删除文件

[英]Remove files from .zip file with Powershell

I am going to write a Powershell script to remove files from a .zip file. 我将编写一个Powershell脚本来从.zip文件中删除文件。 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). 在我的.zip文件中,我有test.txt(最新)test1.txt(较旧)test2.txt .... testN.txt(最旧),所有文件大小不同(或者在powershell中,它叫做Length)。 I want to keep only 2G or smaller of them and remove the rest. 我想只保留2G或更小的剩余部分。 It is required to remove from the oldest ones. 需要从最旧的中删除。 Since the .zip file may be very large. 由于.zip文件可能非常大。 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 : 采用此VBScript解决方案

$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: 如果你安装了.net Framework 4.5,那么这样的东西也应该有效:

[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. 围绕从Entries集合中过滤项目的括号是必需的,否则后续的Delete()将修改集合。 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. 使用7-Zip ,一个免费的Zip工具。 A Technet sample illustrates how to create a zip archive with 7-Zip in Powershell. Technet 示例演示了如何在Powershell中使用7-Zip创建zip存档。

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. 了解正确的命令以获取zip的内容列表,并使用d命令从存档中删除文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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