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

Pay*_*son 3 powershell

我将编写一个Powershell脚本来从.zip文件中删除文件.在我的.zip文件中,我有test.txt(最新)test1.txt(较旧)test2.txt .... testN.txt(最旧),所有文件大小不同(或者在powershell中,它叫做Length).我想只保留2G或更小的剩余部分.需要从最旧的中删除.由于.zip文件可能非常大.最好不要再次提取和拉链.

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

非常感谢.

Ans*_*ers 9

采用此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)
}
Run Code Online (Sandbox Code Playgroud)

如果你安装了.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()
Run Code Online (Sandbox Code Playgroud)

围绕过滤Entries集合中的项目的括号是必需的,否则后续Delete()将修改集合.这样可以防止从集合中读取(从而删除)其他项目.生成的错误消息如下所示:

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