Reputation:
I try to zip files that a are created between 2 dates.
param(
[String]$path="DieserPfadWirdAlsParameterGesetzt"
)
$exclude=@("*.zip")
$currentYear = (Get-Date).AddYears(-1).ToString("yyyy")
$firstDayOfYear = Get-Date -Day 1 -Month 1 -Year $currentYear -Hour 0 -Minute 0 -Second 0
$lastDayOfYear = Get-Date -Day 31 -Month 12 -Year $currentYear -Hour 23 -Minute 59 -Second 59
$files = Get-ChildItem -Path $path -recurse -exclude "$exclude" |
where {
$_.CreationTime -ge $firstDayOfYear -and
$_.CreationTime -lt $lastDayOfYear
}
Compress-Archive -Path $files.FullName -DestinationPath "$path\Archiv$currentYear.zip"
Remove-Item $files.FullName -Recurse -Force -Exclude $exclude
the script works but...
lets say in the directory C:\Users\...\Test
is a folder that was created in 2018 and in that folder is a file that was also created in 2018. The script would create the new zip file (Archiv2018.zip) but in the zip there would be the folder with the file in it AND the file alone...
Is there a way that only the folder with the file in it gets zipped and not the folder with file in it AND file alone?
Upvotes: 0
Views: 947
Reputation: 1255
Your Get-ChildItem
line results in a whole slew of items being returned. Regardless of whenever they are files or folders. You will end up with an array of objects that contains both.
On an abstracted level it will look like this:
If you look at the definition of Compress-Archive
you will find the following description for the -Path
parameter.
Specifies the path or paths to the files that you want to add to the archive zipped file. This parameter can accept wildcard characters. Wildcard characters allow you to add all files in a folder to your zipped archive file. To specify multiple paths, and include files in multiple locations in your output zipped file, use commas to separate the paths.
It doesn't preserve the path if you hand it a single file. As such it will dutifully zip everything within Folder\
and add a.file
and b.file
as well.
To work around this you could specify an additional filter for Get-ChildItem
like -File
or -Directory
to just get files or directories. My guess would be that you just want the files with their respective folder structure.
To make that work you could copy the files to a temporary location and zip the whole temporary location. It would only contain the files you want.
Upvotes: 1
Reputation: 3918
Add -File
to your Get-ChildItem
to only return files:
Get-ChildItem -Path $path -recurse -exclude "$exclude" -File
Upvotes: 1