简体   繁体   中英

Archive Files with Specific Date with Powershell

I've the following task... I want to archive files with an Powershell script that have an specifice creation/edit date. Therefore I started to get a list of these files with the following statemant:

Get-ChildItem -Path C:\Data\... -Recurse | Where-Object { $_.LastWriteTime.Date -gt '2021.01.01' }

This seems to work correctly as I only get the requiered files listed. If I expand the statment to

Get-ChildItem -Path C:\DATA\... -Recurse | Where-Object { $_.LastWriteTime.Date -gt '2021.01.01' } | Compress-Archive -DestinationPath C:\Data\Delta\Archive.zip

the Files that are archived are doubled in the ZIP file. One is the correct set of Files and than all files (also those that are older than the specified date) are added to the archive again.

Can someone tell me what I'm missing?

Thanks in advance

Greatings

Alex

If you want files that have that exact modified date, you need to change operator -gt in the Where-Object clause to -eq .

Also, you should always compare DateTime's to another DateTime object to make sure the string you put in now ('2021.01.01') is converted to a DateTime object properly (that depends very much on your systems culture..)

Then, since you are looking for files in path C:\\DATA and you also create the zip file in that same root path, it is advisable to put brackets around Get-ChildItem to have the collecting of files finish before taking further action on the files. If you don't, the new zip file will also be enumerated.

Try

$refDate = (Get-Date -Year 2021 -Month 1 -Day 1).Date
# filter the files that have an specific last modified date
(Get-ChildItem -Path 'C:\DATA\...' -File -Recurse | Where-Object { $_.LastWriteTime.Date -eq $refDate }) | 
Compress-Archive -DestinationPath 'C:\Data\Delta\Archive.zip'

Or

$refDate = (Get-Date -Year 2021 -Month 1 -Day 1).Date
# filter the files that have an specific last modified date
$files = Get-ChildItem -Path 'C:\DATA\...' -File -Recurse | Where-Object { $_.LastWriteTime.Date -eq $refDate }
$files | Compress-Archive -DestinationPath 'C:\Data\Delta\Archive.zip'

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