2016-05-30 94 views
2

我知道很多关于使用PowerShell压缩文件的内容(并被问到),但尽管我所有的搜索和测试都无法满足需要。PowerShell - 压缩文件夹中的特定文件

按主题我的工作是检查在目录中的特定时间范围

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

创建虽然我能得到我想要/需要我无法找到一个文件的列表文件的脚本方式将它们发送到一个zip文件。

我已经尝试了不同的appraoches像

$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(这将使我的生活变得如此简单)。

我很确定答案相当简单,而且很简单,但我的大脑处于一个循环中,我无法弄清楚如何继续,所以任何帮助都将不胜感激。

回答

3

您可以遍历过滤文件的集合并将它们逐个添加到存档。

# 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() 
+0

正如我所说的,我正在围绕一些非常愚蠢的东西包扎我的头。 我什至试过类似的appraoch,不知道,但我认为它来自你的旧帖子/答案之一,但没有工作。 我已经改变了例子以满足我的具体需求,没有什么恒星我只是指定源文件夹和目标文件夹作为参数,但除此之外它完美地工作! 很多很多谢谢。 – Clariollo