Home ยป How to Delete Folders Older than in PowerShell

How to Delete Folders Older than in PowerShell

To delete folders older than a certain number of days in PowerShell, you can use the Get-ChildItem cmdlet to retrieve a list of folders, filter out folders based on the LastWriteTime property, and then use the Remove-Item command to delete the folders.

The following PowerShell method can be used to delete folders older than x days.

Method 1: Delete folders older than x days in PowerShell

$days = (Get-Date).AddDays(-30)

Get-ChildItem -Path $directoryPath -Directory -Recurse -Force | Where-Object {$_.LastWriteTime -lt $days } | Remove-Item -Force

This example will delete folders older than 30 days specified in the variable $days.

The following example shows how to use this method.

Delete Folder Older than x Days

To delete folders older than x days, use the following PowerShell script that uses the Get-ChildItem and Remove-Item cmdlets.

# Specify the directory path
$directoryPath = "C:\temp\log\"

# Specify cutoff date ( folders than this date will be deleted)
$days = (Get-Date).AddDays(-30)

# Get the folders older than the cutoff daate in the directory and remove those folders
Get-ChildItem -Path $directoryPath -Directory -Recurse -Force | Where-Object {$_.LastWriteTime -lt $days} | Remove-Item -Force
(base) PS C:\>

In this above PowerShell script, the $directoryPath variable holds the directory path. The $days variable stores the cutoff date. The folders older than this date will be deleted.

The Get-ChildItem cmdlet uses the -Directory and -Recurse parameters to retrieve the folders and subfolders from the specified directory path and pipes them to the Where-Object command.

The Where-Object command checks folder’s last write time is less than the cutoff date ($days) and filters folders. The folders to be deleted pipes to the Remove-Item cmdlet forcefully.

Conclusion

I hope the above article on deleting folders than x days in PowerShell is useful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.