1. 程式人生 > 其它 >Powershell按檔案最後修改時間刪除多餘檔案

Powershell按檔案最後修改時間刪除多餘檔案

Sort-Object -Property LastWriteTime -Descending 按照檔案的最後修改時間倒序排列

Select-Object -Skip $count 跳過開頭的$count條資料,取剩餘的資料
$count = 3
$filePathList = "E:\MySql\1",
"E:\MySql\2",
"E:\MySql\3"

foreach($filePath in $filePathList)
{
    $files = Get-ChildItem -Path $filePath | Sort-Object -Property LastWriteTime -Descending | Select-Object -Skip $count
    if ($files.count -gt 0) {
        foreach($file in $files)
        {
            Remove-Item $file.FullName -Recurse -Force
        }
    }    
}

cd D:\FtpServer\小平臺New\Job
ls -Directory|? {$_ -like 'T*'}|del -r

cd D:\web\Dev\SmallPlatformAPI
ls |? {$_ -like 'T*'}

$count = 1
$filePathList = "D:\web\Dev\SmallPlatformAPI"

foreach($filePath in $filePathList)
{
$files = Get-ChildItem -Path $filePath | Sort-Object -Property LastWriteTime -Descending | Select-Object -Skip $count
if ($files.count -gt 0) {
foreach($file in $files)
{
Remove-Item $file.FullName -Recurse -Force
}
}
}

2.刪除目錄內所有檔案修改時間超過timeOutDay的檔案。

$timeOutDay = 30
$filePath = "H:\DataBackup\File\1",
"H:\DataBackup\Database\2"

$allFile = Get-ChildItem -Path $filePath

foreach($file in $allFile)
{
    $daySpan = ((Get-Date) - $file.LastWriteTime).Days
    if ($daySpan -gt $timeOutDay)
    {
        Remove-Item $file.FullName -Recurse -Force
    }
}