Learning and Sharing
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
No Result
View All Result

How to Delete Files Older Than a Specified Number of Days Using PowerShell

July 10, 2024
in A, Blog, Powershell
0
ADVERTISEMENT

Table of Contents

Delete Files Older Than a Specified Number of Days

In some cases, you want to delete files older than specified number of days. For example, you want to clean up the backup directory to keep only recent backup files.

bzxZ7eGB4PYkRlD5EdaJPCDcGiOKFKGkIvkS78sdK4MXEi4tpEPCz4AknprF

Simple PowerShell script

To do it, we’ve created a simple PowerShell script to manage and delete files based on their age.

  • It offers the option to delete files older than a specified number of days, for example 7 days.
  • The script uses the path -Recurse command, commonly referred to as recurse, to delve deep into directories, ensuring it scans all child folders where files are located, be it on a local machine or a shared drive path.
  • It does this by comparing the LastWriteTime attribute of each file against the current date. If a file’s age surpasses the set threshold, such as files older than 7 days using specific criteria, it becomes a candidate for deletion.
  • You can modify the (Get-Date).AddDays(-X) part of the PowerShell script, where X is the number of days. This allows you to specify the exact number of days you’d like to use as a threshold for deletion.
  • You can replace LastWriteTime with CreationTime in the script to filter files based on their creation date instead.

For those who might be dealing with old log files or any content that’s been sitting untouched for the last 30 days, the script is the answer you’re looking for. It provides an efficient way in Windows PowerShell to delete files older than some days, ensuring that only outdated content is removed.

# The location to scan
$location = "D:\Backup"

# Calculate the cutoff date
$cutoffDate = (Get-Date).AddDays(-7)

# Find files older than the specified duration
$oldFiles = Get-ChildItem -Path $location -Recurse -File | Where-Object { $_.LastWriteTime -lt $cutoffDate }

$i = 1
$oldFiles | ForEach-Object {
    Write-Progress -PercentComplete ($i/$($oldFiles.Count)*100) -Status "Deleting file: $($_.FullName)" -Activity "Processing: ($i/$($oldFiles.Count))"
    Remove-Item $_.FullName -Force
    $i++
    Start-Sleep -Milliseconds 500
}

You can run the code directly in the PowerShell console or create a PowerShell script for later use.

9pJhbh2KeghTgojicU8FZOtSn8DI6FVYN8LZWNVCDM5x2XhaA2UuD2zPSyMm

Tips: By creating a scheduled task in Windows, you can run the PowerShell script at regular intervals to automate the deletion of old files.

As you can see, the old backup files are deleted automatically.

gmo8XQojull92DoCYubmXOM4eyJLUC6YEndjV0iD2lh7newADy6a3b46JUCa

Advanced PowerShell script

Additionally, we can customize the script to delete the old files from any directory and specify any number of dates for deletion. When running the script:

  • It will ask you to enter the path of the directory that you want to delete the old files from.
  • Prompt you to enter the any number of dates for deletion.
  • Confirm the deletion: 1 for delete, 2 for do nothing.
# Prompt user for the location to scan
$location = Read-Host "Enter the location to scan for files and folders"
$location = ($location).trim('"')
$location = ($location).trim("'")

# Prompt user for the duration (older than how many days)
$days = Read-Host "Enter the duration (older than how many days)"

# Prompt user for the action (1 for delete, 2 for do nothing)
$action = Read-Host "Enter the action (1 for delete, 2 for do nothing)"

# Calculate the cutoff date
$cutoffDate = (Get-Date).AddDays(-$days)

# Find files older than the specified duration
$oldFiles = Get-ChildItem -Path $location -Recurse -File | Where-Object { $_.LastWriteTime -lt $cutoffDate }

# Find folders older than the specified duration
$oldFolders = Get-ChildItem -Path $location -Recurse -Directory | Where-Object { $_.LastWriteTime -lt $cutoffDate }

# Take action based on user's choice
if ($action -eq "1") {
    $i = 1
    $oldFiles | ForEach-Object {
        Write-Progress -PercentComplete ($i/$($oldFiles.Count)*100) -Status "Deleting file: $($_.FullName)" -Activity "Processing: ($i/$($oldFiles.Count))"
        Remove-Item $_.FullName -Force
        $i++
        Start-Sleep -Milliseconds 500
    }
} elseif ($action -eq "2") {
    Write-Host "No action taken. There are $($oldFiles.Count) files older than $days days" -ForegroundColor Yellow
} else {
    Write-Host "Invalid action selected." -ForegroundColor Yellow
}

The output when running the script on our computer.

6LiojFP61Uo6i5mRCq7vTOuAj5gYiPu3nh83t9ap7fhaxsF6NrO34RQqWkg4
FOIXdkTawWH4ZPNF6QwGsbpe6quRvC2TEFt7o0mkQyKtwbm1rmkcrEA5xdSr
ADVERTISEMENT

Not a reader? Watch this related video tutorial:

5/5 - (1 vote)
Previous Post

How To Stop Teams from Changing from Available to Away Status Automatically

Next Post

How to Get Date Without Time in PowerShell

Related Posts

Images Hidden Due To Mature Content Settings In CivitAI

August 31, 2024

Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

August 20, 2024

Running Hyper-V and VMware Workstation on The Same Machine

August 15, 2024

How to Uninstall All Autodesk Products At Once Silently

July 29, 2024
Ftr5

How to Uninstall the Autodesk Genuine Service on Windows

July 29, 2024

How to Remove The Test Mode Watermark Without Disabling Test Mode

July 28, 2024

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How To Turn On uBlock Origin Extension in Chrome (2025)
  • Images Hidden Due To Mature Content Settings In CivitAI
  • Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

Categories

Stay in Touch

Discord Server

Join the Discord server with the site members for all questions and discussions.

Telegram Community

Jump in Telegram server. Ask questions and discuss everything with the site members.

Youtube Channel

Watch more videos, learning and sharing with Leo ❤❤❤. Sharing to be better.

Newsletter

Join the movement and receive our weekly Tech related newsletter. It’s Free.

General

Microsoft Windows

Microsoft Office

VMware

VirtualBox

Technology

PowerShell

Microsoft 365

Microsoft Teams

Email Servers

Copyright 2025 © All rights Reserved. Design by Leo with ❤

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory