2016-05-30 149 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