删除除特定文件以外的旧文件。目录正在删除

时间:2017-03-13 12:26:33

标签: powershell

我有一个脚本可以删除超过14天的文件,除非该文件被称为test.dll

问题是,如果文件夹超过14天但文件很小,比如两天,则文件夹和文件将被删除。如何修复此问题,以便在文件存在时不删除文件夹?

该文件可以位于树中的任何子目录中。基本上我希望它删除超过14天的所有文件和文件夹,除了test.dll之外,它们位于子目录结构中。

这是我使用的脚本:

$Now = Get-Date
$Days = "14"
$TargetFolder = "E:\Web2\testdir"
$Extension = "*.*"
$LastWrite = $Now.AddDays(-$Days)

#---- get files based on lastwrite filter and specified folder ----!
$Files = Get-ChildItem $TargetFolder -Exclude "test.dll" -Recurse |
         Where {$_.LastWriteTime -le "$LastWrite"}

#---- For each file in $TargetFolder folder, run a foreach loop and delete the file
if ($Files) {
    foreach ($File in $Files) {
        if ($File -ne $null) {
            Write-Host "Deleting File $File" -ForegroundColor "DarkRed"
            Remove-Item $File.FullName -Recurse -Force -ErrorAction SilentlyContinue | Out-Null
        } else {
            Write-Host "No more files to delete!" -ForegroundColor "Green"
        }
    }
} else {
    Write-Host "There are no files older than $Days days old in $TargetFolder" -ForegroundColor "Green"
}

1 个答案:

答案 0 :(得分:3)

收集文件列表时,将-File参数传递给Get-ChildItem

$Files = Get-ChildItem $TargetFolder -File -Exclude "test.dll" -Recurse