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

标签 powershell

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

有没有办法实现这一目标?

非常感谢。

最佳答案

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

如果您安装了 .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()

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

枚举集合时出错:集合已修改;
枚举操作可能无法执行..
在行:1 字符:1
+ $zip.Entries | ? { $filesToRemove -包含 $_.Name } | % { $_.Delete() }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Collecti...ipArchiveEntry]:Enumerator) [], RuntimeException
+ FullQualifiedErrorId : BadEnumeration

关于powershell - 使用 Powershell 从 .zip 文件中删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20269202/

相关文章:

rest - 使用 Powershell 更新 GoDaddy API 上的 DNS 记录时出现错误 422

powershell - 从 Powershell 脚本最大化打开 IE?

c# - 如何使用 C# 检查是否安装了 PowerShell

azure - Connect-AzureAD -确认抛出 AADSTS900144 : The request body must contain the following parameter: 'code' . 错误

xml - 如何在powershell中从xml获取特定字符串

powershell - 找不到接受参数 'Files\'的位置参数

powershell - 比较参数无法正常工作

powershell - Powershell如何将结果同时输出到多个文件中?

powershell - Azure Powershell Keyvaults - 返回多个 SecretValueText 返回 null

azure - 确保 azure pipeline 构建的 dll 和 nuget 包包含与 csproj 版本相同的信息