我正在尝试删除超过特定日期的文件夹。这些文件夹是一个zip文件,其布局如下:
<Zip Folder>
<Folder 1>
<Folder 2>
<Folder 3>
<Folder 4>
文件夹2,3和4可能不需要全部删除,所以我不能只删除主zip文件。我试过这个,但似乎什么也没做:
function DeleteAuditFiles{
# The two parameters.
param([string]$limit, [string]$path)
$zips = Get-ChildItem -Path $path -recurse *.zip
foreach ($zipfile in $zips) {
$stream = New-Object IO.FileStream($zipfile.FullName, [IO.FileMode]::Open)
$mode = [IO.Compression.ZipArchiveMode]::Update
$zip = New-Object IO.Compression.ZipArchive($stream, $mode)
($zip.Entries | ? { $_.PSIsContainer -and $_.CreationTime -lt $limit }) | % { $_.Delete() }
$zip.Dispose()
$stream.Close()
}
}
答案 0 :(得分:3)
我必须添加一个类型才能使用IO.Compression.ZipArchive
:
Add-Type -AssemblyName System.IO.Compression
看看是否有效:
$toDelete = $zip.Entries | where{ $_.name -eq "" -and $_.LastWriteTime -lt $limit }
$toDelete | % { $_.Delete() }
我使用了一个变量,因为你需要首先在列表中获取要删除的所有文件夹,如果你在枚举时删除,Powershell会抱怨异常:
An error occurred while enumerating through a collection: Collection was modified; enumeration operation may not execute..