sasquach007
sasquach007

Reputation: 11

Delete old files except for a certain file. Directory is being deleted

I have a script that deletes files older than 14 days unless the file is called test.dll.

The problem is that if the folder is older than 14 day but the file is young, say two days old, the folder and file are being deleted. How can I fix this so the folder is not deleted if the file exists?

The file can be in any sub directory in the tree. Basically I want it to delete all files and folders older than 14 days except test.dll whereever it lives in the sub directory structure.

Here is the script I was using:

$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"
}

Upvotes: 1

Views: 1221

Answers (1)

arco444
arco444

Reputation: 22831

Pass the -File parameter to Get-ChildItem when you collect a list of your files:

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

Upvotes: 3

Related Questions