簡體   English   中英

使用 Powershell 歸檔具有特定日期的文件

[英]Archive Files with Specific Date with 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 文件中加倍。 一個是正​​確的文件集,然后所有文件(以及那些早於指定日期的文件)都會再次添加到存檔中。

有人可以告訴我我錯過了什么嗎?

提前致謝

嘉年華

亞歷克斯

如果您想要具有該確切修改日期的文件,則需要將 Where-Object 子句中的運算符-gt更改為-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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM