我将编写一个 Powershell 脚本来从 .zip 文件中删除文件。
在我的 .zip 文件中,我有
test.txt(最新)
test1.txt(较旧)
测试2.txt
....
testN.txt(最旧的),
都具有不同的文件大小(或在 powershell 中,它被称为长度)。
我只想保留其中的 2G 或更小,并删除其余的。需要从最旧的中删除。
由于 .zip 文件可能非常大。最好不要提取它并再次压缩。
有没有办法实现这一目标?
非常感谢。
最佳答案
$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/