delete files in a subfolder in scdule time

Meysam Salary 0 Reputation points

I have two folder- A and B

B is subfolder of A and inside B there many files , i want to delete files inside B more that x days without delete Folder B , is there any solution


Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,405 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Marcin Policht 13,480 Reputation points MVP

    Try the following:

    # Define the root folder path
    $rootFolderPath = "C:\Path\to\folder\A"
    # Define the maximum age of files to keep (in days)
    $maxAgeInDays = 30
    # Get the current date
    $currentDate = Get-Date
    # Define the subfolder path
    $subfolderPath = Join-Path -Path $rootFolderPath -ChildPath "B"
    # Get files in the subfolder older than the specified age
    $filesToDelete = Get-ChildItem -Path $subfolderPath -File | Where-Object {
        $_.LastWriteTime -lt ($currentDate.AddDays(-$maxAgeInDays))
    # Delete the files
    foreach ($file in $filesToDelete)

    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.