2018-05-03

利用 PowerShell 刪除某路徑底下 14 天以前的檔案與資料夾 (過期檔案與資料夾)

寫過一篇 用批次檔 (Batch) 刪除指定天數之前 (過期) 所有子目錄及檔案

以下改用 PowerShell 處理, 邏輯:

1. 找出過期檔案予以刪除
2. 找出過期的空資料夾予以刪除 (從最深層的子目錄開始往上一層一層檢查)

不知道是否需要寫得這麼複雜就是了

============ 程式開始============

#Days Before to Delete
$Days = "14";

# Path To Process (Recurse)
$TargetFolder = "C:\TargetFolder";

$Excepts = @()

# Except Files and Folders Name
$Excepts += "!!_Readme.txt"
$Excepts += "!!_Caution.txt"


# ------------------------------------------------------------------

if (!(Test-Path -path $TargetFolder)) {
Write-Host "$TargetFolder not Exist!";
exit;
};

$LastWrite = $(Get-Date).AddDays(-$Days);

# Delete Files

$Items = Get-Childitem $TargetFolder -File -Recurse | Where {$_.LastWriteTime -le $LastWrite};

foreach ($Item in $Items) {
    if ($Item -ne $NULL) {
$Exception = 0
foreach ($Except in $Excepts) {
if ($Item.Name -eq $Except) {
$Exception = 1
};
};
if ($Exception -eq 0) {
Remove-Item $Item.FullName -Force -ErrorAction SilentlyContinue;
Write-Host "Remove ""$($Item.FullName)"""
};
    };
};

# Delete Empty Folders

$TargetDeep = $($($TargetFolder.Split("\")).Count-1)
$ItemDeep = 0
$CurrentDeep = 1

Do {
$Items = Get-Childitem $TargetFolder -Directory -Recurse | Where {($_.LastWriteTime -le $LastWrite) -and ( (Get-Childitem $_.FullName).Count -eq 0) }

foreach ($Item in $Items) {
if ($Item -ne $NULL) {
$Exception = 0
foreach ($Except in $Excepts) {
if ($Item.Name -eq $Except) {
$Exception = 1
};
};
if ($Exception -eq 0) {
Remove-Item $Item.FullName -Force -ErrorAction SilentlyContinue;
Write-Host "Remove ""$($Item.FullName)"""
$NowItemDeep = $($($($Item.FullName).Split("\")).Count-$TargetDeep-1)
if ($NowItemDeep -gt $ItemDeep) {
$ItemDeep = $NowItemDeep
};
};
};
};
$CurrentDeep += 1;
} while ($CurrentDeep -le $ItemDeep);

沒有留言: