powershell - 使用 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 文件中加倍。一个是正确的文件集,然后所有文件(还有那些早于指定日期的文件)都会再次添加到存档中。
有人可以告诉我我错过了什么吗?
提前致谢
伟大的
亚历克斯
解决方案
如果您想要具有确切修改日期的文件,则需要-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'
推荐阅读
- r - 获取每行的非零和行的矩阵行索引和列索引
- python-3.x - 错误:builtin_function_or_method' 对象在 python 中不可下标
- python - 有没有一种计算效率更高的方法来使用 Pandas 找到匹配正则表达式的第一个匹配项?
- jquery - 在表查询中查找值
- javascript - 如何访问车把中的 app.locals 变量
- google-bigquery - Big Query 统一费率定价中复制、加载和导出操作的槽利用
- python - ValueError:模型的输出张量必须是 Keras `Layer` 的输出
- c# - 删除基于数据的数据网格视图
- php - Laravel 没有在单元测试中引导 trait/authing 用户
- javascript - 从 Node.js 流中写入多个文件