delete files in a subfolder in scdule time

Meysam Salary 0 Reputation points
2024-04-28T10:02:38.3666667+00:00

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

Thnx

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,390 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Marcin Policht 12,320 Reputation points MVP
    2024-04-28T11:14:28.3233333+00:00

    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.

    hth

    Marcin