簡體   English   中英

使用Powershell從.zip文件中刪除文件

[英]Remove files from .zip file with Powershell

我將編寫一個Powershell腳本來從.zip文件中刪除文件。 在我的.zip文件中,我有test.txt(最新)test1.txt(較舊)test2.txt .... testN.txt(最舊),所有文件大小不同(或者在powershell中,它叫做Length)。 我想只保留2G或更小的剩余部分。 需要從最舊的中刪除。 由於.zip文件可能非常大。 最好不要再次提取和拉鏈。

有沒有辦法實現這個目標?

非常感謝。

采用此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,那么這樣的東西也應該有效:

[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()將修改集合。 這樣可以防止從集合中讀取(從而刪除)其他項目。 生成的錯誤消息如下所示:

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

使用7-Zip ,一個免費的Zip工具。 Technet 示例演示了如何在Powershell中使用7-Zip創建zip存檔。

了解正確的命令以獲取zip的內容列表,並使用d命令從存檔中刪除文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM