Powershell – Deleting files in sub-directories, excluding root directory

powershell

I have written a Powershell script that is supposed to delete files in sub-directories that are older than 25 days.

#
# Variables.
#
$days = 25
$src = "C:\Users\ArifSohM\Desktop\TestFolder\"

# Check if files are older than 25 days.

Get-childitem -path $src |
ForEach-Object {
    $age = New-Timespan ($_.LastWriteTime) $(get-date)

    if($age.days -gt $days) {
    Remove-Item $_.FullName -force
    Write-host "$_ is older than 25 days and has been deleted." -ForegroundColor yellow
    }
}
#

This works partially fine, but when I run this command it also deletes files in the root directory. This is my folder structure:

  • Test Folder (Root)
    • Directory1 (Folder)
      • File1
      • File2
    • Directory2 (Folder)
      • File1
      • File2
    • File1
    • File2

So, I want to delete everything in Directory1 & Directory2, but not in Test Folder. Can this be done?

Best Answer

This can be done (among other ways) by using Get-ChildItem -Directory to select only directories, and the cycling through them.

Note that your/my function will not handle sub-folders inside sub-folders. This is just a simple adjustment of your original script.

$days = 25
$src = "C:\Users\ArifSohM\Desktop\TestFolder\"

# Check if files are older than 25 days.

$dirs = Get-childitem -path $src* -Directory 

foreach ($dir in $dirs) {
    Get-childitem -path $dir | ForEach-Object {
        $age = New-Timespan ($_.LastWriteTime) $(get-date)

        if($age.days -gt $days) {
        Remove-Item $_.FullName -force
        Write-host "$_ is older than 25 days and has been deleted." -ForegroundColor yellow
        }
    }
}