PowerShell delete files in folder older than specific date. | How to remove files from folder using PowerShell?

This article guides.

How to remove files from folder using PowerShell? or PowerShell delete files in folder older than specific date.

Sometimes you need to delete old files from particular folder. There are many scenarios where you have to delete those files like deletion based on last modified or deletion based on file name etc.

You will have many subfolders inside primary folder, and you need to delete files recursively from each sub folders.

There are many ways to delete files like you can delete manually, using batch scripts. PowerShell is one of the way to delete files from folder recursively. PowerShell script is faster in execution and also delete files from all subfolders.

You can define condition in PowerShell script to delete files.

What is PowerShell?

PowerShell is a command-line shell and scripting language built on the .NET Framework. It is designed for system administrators and power users to automate tasks and manage Windows systems more efficiently. PowerShell includes a command-line interface and a scripting language, and it can be used to automate tasks, manage systems, and access data. It can also be used to access and manage other Microsoft products, such as Exchange, SharePoint, and Azure.

Below script can help you to delete files from folders and subfolders recursively.

Delete Files from folder with particular extension like .bak

#Delete files from folders with particular extension
$sourceFolder = 'C:\SQL2019\backup\*'

Get-ChildItem $sourceFolder -Recurse  | Where-Object {$_.Name -like '*.bak'} | Remove-Item #Change file extension.

Before deletion:

After Deletion :

PowerShell delete files in folder older than specific date.

Below script can help to delete files from folder older than specific date along with specific file extension. You can change date and file extension in script as per your requirement.

Before deletion :

Watch Step by step guide. How to remove files from folder using PowerShell?

Below script will list filenames in folder need to be deleted based on date mentioned in script.

$datedeletion = [datetime]::ParseExact('2022-12-24','yyyy-MM-dd', $null)

$sourceFolder = 'C:\Omkar\backups\backup\*'

Get-ChildItem $sourceFolder -Recurse  | Where-Object { $_.CreationTime -lt $datedeletion -and $_.Name -like '*.bak'} | select name #| Remove-Item
Below Script will delete files from folder and sub folders.
#Delete files from folders based on date

$datedeletion = [datetime]::ParseExact('2022-12-24','yyyy-MM-dd', $null)

$sourceFolder = 'C:\Omkar\backups\backup\*'

Get-ChildItem $sourceFolder -Recurse  | Where-Object { $_.CreationTime -lt $datedeletion -and $_.Name -like '*.bak'} | Remove-Item

Files deleted successfully.

Leave a Comment