首页 > 解决方案 > 使用 Powershell 归档具有特定日期的文件

问题描述

我有以下任务...我想使用具有特定创建/编辑日期的 Powershell 脚本存档文件。因此,我开始使用以下声明获取这些文件的列表:

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

这似乎工作正常,因为我只列出了所需的文件。如果我将语句扩展为

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

归档的文件在 ZIP 文件中加倍。一个是正​​确的文件集,然后所有文件(还有那些早于指定日期的文件)都会再次添加到存档中。

有人可以告诉我我错过了什么吗?

提前致谢

伟大的

亚历克斯

标签: powershell

解决方案


如果您想要具有确切修改日期的文件,则需要-gt将 Where-Object 子句中的运算符更改为-eq.

此外,您应该始终将 DateTime 与另一个 DateTime 对象进行比较,以确保您现在输入的字符串('2021.01.01') 正确转换为 DateTime 对象(这在很大程度上取决于您的系统文化......)

然后,由于您正在查找路径中的文件,C:\DATA并且您还在同一根路径中创建了 zip 文件,因此建议在Get-ChildItem对文件采取进一步操作之前将括号括起来以完成文件收集。如果不这样做,新的 zip 文件也将被枚举。

尝试

$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'

或者

$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'

推荐阅读