剛剛撰寫了 Powershell 腳本,該腳本將在子檔案夾中查找有關檔案的名稱,該檔案的名稱中包含 1 分鐘前創建的“.doc_”,然后將其移動到另一個子檔案夾。
當我運行 powershell 腳本時,它會移動 1 分鐘前創建的名稱中帶有“.doc_”的檔案,但也會移動幾天前創建的名稱中帶有“.doc_”的相同檔案,這不是必需的。
您能否讓我知道為什么我的代碼考慮了超過 1 分鐘的檔案
get-childitem -Path "C:\Users\Administrator\Desktop\Test\Test2" | where-object {$_.Name -match ".doc_" -and $_.LastWriteTime -lt (get-date).Adddays(-0) -and $_.LastWriteTime -lt (get-date).AddMinutes(-1)}| move-item -destination "C:\Users\Administrator\Desktop\Test"
uj5u.com熱心網友回復:
簡而言之,您的過濾器Get-Date是錯誤的,因為它在1 分鐘前抓取了所有內容。這是由于-lt運營商,如果您與-gt運營商交換它應該可以作業。
好的,下一個話題。由于您實際上不是在檔案中搜索特定單詞,而是在檔案名中搜索,我們可以使用FileSystem Provider 來過濾該檔案名,我們將犧牲RegEx(使用 -match),使用通配符運算式;這將使速度提高 40 倍,因為通過管道發送任何內容都非常昂貴:
Get-ChildItem -Path "C:\Users\Administrator\Desktop\Test\Test2" -Filter "*.doc_*" |
where-object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-1) } |
Move-Item -Destination "C:\Users\Administrator\Desktop\Test"
如果時間很重要,我們可以嘗試使用分組運算子( .. )和.Where({})運算子/方法來避免管道。
- 由于它不會對物件本身執行任何直接操作,因此它更像是一個運算子。
(Get-ChildItem -Path "C:\Users\Administrator\Desktop\Test\Test2" -Filter "*.doc_*").Where{
$_.LastWriteTime -gt (Get-Date).AddMinutes(-1)
} | Move-Item -Destination "C:\Users\Administrator\Desktop\Test"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/358641.html
