用PowerShell刪除檔案/資料夾

摘要:刪除檔案/資料夾

刪除檔案

#取得現在時間
$Now = Get-Date 
#定義要刪除的天數
$Days = "14"
#定義路徑
$TargetFolder = "C:\log"
#定義副檔名
$Extension = ".log"
#定義要刪除的日期 (刪除今天往前Days的log)
$LastWrite = $Now.AddDays(-$Days)

$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}

foreach ($File in $Files) 
{
    if ($File -ne $NULL)
    {
        write-host "Deleting File $File" -ForegroundColor "DarkRed"
        Remove-Item $File.FullName | out-null
    }
    else
    {
        Write-Host "No more files to delete!" -foregroundcolor "Green"
    }
}

刪除資料夾

#定義要刪除的天數
$Days = 14

#定義要刪除多久以前的資料夾
$Target = ((Get-Date).AddDays(-$Days)).ToString("yyyy-MM-dd")

#定義主目錄
$TargetFolder = "C:\backup"

#取得主目錄底下的所有目錄
$Dirs = Get-Childitem $TargetFolder 

foreach ($Dir in $Dirs) 
{
    #目錄的命名方式為 bakup_2014-07-24 10,00,00,所以用正規表示法取中間的日期字串
    $Dir -match'.*(\d\d\d\d-\d\d-\d\d).*' > $nul
    #index 1為日期部分
    #$Matches[1]
    #日期小於target就將整個資料夾刪除
    if ($Matches[1] -le $Target)
    {
        #write-host "Deleting File $File" -ForegroundColor "DarkRed"
        write-host "Start deleting Dir $Dir" -ForegroundColor "DarkRed"
        Remove-Item $Dir.FullName -Force -Recurse
        write-host "Finish Deleting Dir $Dir" -ForegroundColor "DarkRed"
    }

}