.net PowerShell-在文件夹中压缩特定文件

.net PowerShell-在文件夹中压缩特定文件,.net,powershell,zip,powershell-4.0,.net,Powershell,Zip,Powershell 4.0,我知道有很多关于使用PowerShell压缩文件的文章(也有人问过),但是尽管我进行了所有的搜索和测试,我还是无法找到我需要的东西 根据主题,我正在编写一个脚本,用于在目录中检查在特定时间范围内创建的文件 $a= Get-ChildItem - path $logFolder | Where-Object {$_.CreationDate -gt $startDate -and $_.CreationDate -lt $endDate} 虽然我可以得到我想要/需要的文件列表,但我找不到

我知道有很多关于使用PowerShell压缩文件的文章(也有人问过),但是尽管我进行了所有的搜索和测试,我还是无法找到我需要的东西

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

   $a= Get-ChildItem - path $logFolder | 
Where-Object {$_.CreationDate -gt $startDate -and $_.CreationDate -lt $endDate}
虽然我可以得到我想要/需要的文件列表,但我找不到将它们发送到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()

正如我所说的,我当时脑子里想的是一件非常愚蠢的事情。我甚至尝试过类似的方法,不确定,但我认为这是来自你以前的一篇帖子/答案,但不起作用。我已经修改了这个示例以满足我的特定需求,我只是简单地将源文件夹和目标文件夹指定为一个参数,但除此之外,它工作得非常好!非常感谢。