I prefer to use the System.IO.Compression
library for flexibility. You can specify the relative path within the zip file, and keep the file open for efficient writing if you prefer. However, based on your requirements it seems there will be multiple zip files (one per child folder), so I'd recommend closing the zip with Dispose()
after each write. Here's an untested and inefficient example that will do what you say:
@( 'System.IO.Compression','System.IO.Compression.FileSystem') | % { [void][Reflection.Assembly]::LoadWithPartialName($_) }
Set-Location '.\2022'
$FilesToZip = Get-ChildItem 'L0283*' -File -Recurse | ?{$_.Name -notlike '*.zip'}
ForEach($file in $FilesToZip){
Try{
Set-Location $file.Directory.FullName #change to the folder where the file exists
$WriteArchive = [IO.Compression.ZipFile]::Open( '.\400401_L0283408archive.zip', 'Update')#Update mode adds files to new or existing zip
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($WriteArchive, $file.FullName, $file.Name, 'Optimal')
}Finally{
$WriteArchive.Dispose() #close the zip file so it can be read later
}
}
$FilesToZip = Get-ChildItem 'L0284*' -File -Recurse | ?{$_.Name -notlike '*.zip'}
ForEach($file in $FilesToZip){
Try{
Set-Location $file.Directory.FullName #change to the folder where the file exists
$WriteArchive = [IO.Compression.ZipFile]::Open( '.\400401_L0284408archive.zip', 'Update')#Update mode adds files to new or existing zip
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($WriteArchive, $file.FullName, $file.Name, 'Optimal')
}Finally{
$WriteArchive.Dispose() #close the zip file so it can be read later
}
}
It's inefficient because it opens and closes the archive with each write. I repeated code for simplicity, but if I had control over the zip file structure I would rewrite this script to create a single zip containing all the files while preserving the relative path, like I mentioned in this answer.
EDIT: I added a filter to prevent zipping *.zip files: | ?{$_.Name -notlike '*.zip'}
Please try with this filter.