PowerShell - 将特定文件压缩到文件夹中

PowerShell - Zip specific files in a folder

我知道有很多关于使用 PowerShell 压缩文件的文章(和询问),但尽管我进行了所有搜索和测试,但我无法提出我需要的东西。

根据主题,我正在编写一个脚本,用于检查在特定时间范围内创建的文件的目录

   $a= Get-ChildItem - path $logFolder | 
Where-Object {$_.CreationDate -gt $startDate -and $_.CreationDate -lt $endDate}

虽然我可以获得文件列表,但我 want/need 我找不到将它们发送到 zip 文件的方法。

我尝试过不同的方法,例如

$sourceFolder = "C:\folder1"
$destinationZip = "c:\zipped.zip" 
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourceFolder, $destinationZip)

虽然这在压缩文件夹时效果很好,但这不是我想要的,当然我可以将文件移动到一个临时文件夹并压缩它,但看起来很浪费,我相信有更好的方法这样做。

请记住,我不能使用 7zip 等第三方工具,我不能使用 PowerShell 扩展或 PowerShell 5(这会让我的生活变得更轻松)。

我很确定答案相当简单,而且一目了然,但我的大脑处于循环状态,我不知道如何继续,因此非常感谢您的帮助。

您可以遍历过滤后的文件集合,并将它们一个接一个地添加到存档中。

# creates empty zip file:
[System.IO.Compression.ZipArchive] $arch = [System.IO.Compression.ZipFile]::Open('D:\TEMP\arch.zip',[System.IO.Compression.ZipArchiveMode]::Update)
# add your files to archive
Get-ChildItem - path $logFolder | 
Where-Object {$_.CreationDate -gt $startDate -and $_.CreationDate -lt $endDate} | 
foreach {[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($arch,$_.FullName,$_.Name)}
# archive will be updated with files after you close it. normally, in C#, you would use "using ZipArchvie arch = new ZipFile" and object would be disposed upon exiting "using" block. here you have to dispose manually:
$arch.Dispose()