Home ยป How to Delete Files Older than in PowerShell

How to Delete Files Older than in PowerShell

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

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

Method 1: Delete files older than x days in PowerShell

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

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

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

The following example show how to use this method.

Delete Files Older than x Days

To delete files 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 ( files older than this date will be deleted)
$days = (Get-Date).AddDays(-30)

# Get the files older than the cutoff daate in the directory and remove those files
Get-ChildItem -Path $directoryPath -File -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 files older than this date will be deleted.

The Get-ChildItem cmdlet retrieves the files from the folder and subfolders for the specified directory path and pipes them to the Where-Object where it checks file’s last write time is less than the cutoff date ($days) and filters files. The files to be deleted pipes to the Remove-Item cmdlet forcefully.

Conclusion

I hope the above article on deleting files older 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.