简体   繁体   中英

PowerShell - Zip specific files in a folder

I know a lot has been written (and asked) about zipping files with PowerShell but despite all my searches and tests I could not come up with what I need.

As per subject I'm working on a script that check a in directory for files created in a specific time range

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

While I can get the list of files I want/need I cannot find a way to send them to a zip file.

I've tried different appraoches like

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

But while this works well when zipping a folder it's not what I'm looking for, sure enough I could move files to a temporary folder and zip that but looks like a waste and I'm sure there are better ways of doing this.

Keep in mind I cannot use use third party tools like 7zip etc., I cannot use PowerShell extensions nor PowerShell 5 (which would make my life all so easier).

I'm pretty sure answer is rather easy and in plain sight but my brain is in a loop and I cannot figure out how to proceed so any help would be much appreciated.

You can loop through the collection of filtered files and add them one-by-one to an archive.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM