Powershell :: delete file by last modify date

之前有過一個需求是要能夠將分享的資料夾內的資料僅保留最近30天 其實很多方式都可以達到比如 Robocopy, PowerShell 這次選PowerShell 作為主要工具來刪除檔案 首先我們要取得資料夾內的所有檔案,判斷就用檔案的最後修改日期

Code:

$paths = "C\TEST"
Get-ChildItem -File -Recurse $paths | Where-object {$_.LastWriteTime -lt (get-date).adddays(-30) } | % {
 $_.FullName
}

這樣的話我們就已經可以知道所有超過30天以上的檔案是什麼了 如過要刪除檔案的話 就加上 Remove-Item (詳閱: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/remove-item?view=powershell-6)

Code :

$paths = "C\TEST"
Get-ChildItem -File -Recurse $paths | Where-object {$_.LastWriteTime -lt (get-date).adddays(-30) } | % {

 $_.FullName
 Remove-Item $_.FullName

}

想要再刪除檔案前先備份一下,就加上 Copy-Item(詳閱:https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/copy-item?view=powershell-6) 在 Remove-Item 之前

Code :

Get-ChildItem -File -Recurse $paths | Where-object {$_.LastWriteTime -lt (get-date).adddays(-30) } | % {

 $_.FullName
 Copy-Item  $_.FullName "c:\Test_Backup"
 Remove-Item $_.FullName

}

留言

這個網誌中的熱門文章

Easy Triangle Calculator

Swift Sprite Kit easy to create bullet

Powershell transfert UPS Worldship address book to csv file for UPS web import