简体   繁体   English

使用 Powershell 归档具有特定日期的文件

[英]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.我有以下任务......我想使用具有特定创建/编辑日期的 Powershell 脚本存档文件。 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.存档的文件在 ZIP 文件中加倍。 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 .如果您想要具有该确切修改日期的文件,则需要将 Where-Object 子句中的运算符-gt更改为-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..)此外,您应该始终将 DateTime 与另一个 DateTime 对象进行比较,以确保您现在输入的字符串('2021.01.01') 正确转换为 DateTime 对象(这在很大程度上取决于您的系统文化......)

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.然后,由于您要在路径C:\\DATA中查找文件,并且还在同一根路径中创建了 zip 文件,因此建议在Get-ChildItem周围放置方括号,以便在对文件执行进一步操作之前完成文件收集文件。 If you don't, the new zip file will also be enumerated.如果不这样做,新的 zip 文件也将被枚举。

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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