使用 Powershell 从 .zip 文件中删除文件 [英] Remove files from .zip file with Powershell

查看:37
本文介绍了使用 Powershell 从 .zip 文件中删除文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将编写一个 Powershell 脚本来从 .zip 文件中删除文件.在我的 .zip 文件中,我有test.txt(最新)test1.txt(较旧)测试2.txt....testN.txt(最旧的),都具有不同的文件大小(或在 powershell 中,它被称为长度).我只想保留其中的 2G 或更小,并删除其余的.需要从最旧的中删除.由于 .zip 文件可能非常大.最好不要解压再压缩.

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?

非常感谢.

推荐答案

采用这个 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)
}

<小时>

如果您安装了 .net Framework 4.5,这样的东西也应该可以工作:


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

Entries 集合中过滤项的括号是必需的,否则后续的 Delete() 会修改集合.这将阻止从集合中读取(并因此删除)其他项目.生成的错误消息如下所示:

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

这篇关于使用 Powershell 从 .zip 文件中删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆