Pipe the filtered list of files to the Remove-Item value to perform deletion of those files.In this example, the threshold is 14 days. Filter the output to include only files whose CreationTime value is older than the number of days saved in the $threshold variable.Get the collection of files located in the folder specified in the $path variable.
The next line of code after the $threshold variable will: The value of the $threshold the age in days that the file to be deleted must be. Then, the second line is where the threshold is specified. The first line defines the path for Get-ChildItem to search. In this example script below, files in C:\temp whose CreationTime value is older than the set threshold will be deleted. Now that you know which files to remove, you can create a script to only delete files that are older than a specific number of days – in this case, older than 492 days. Important: Before deleting any temporary files from your PC, you should first close all. If you want to delete everything in your temp folder, press Ctrl + A to select all the items. Hold Ctrl and click individual items to select them for cleanup. Get-ChildItem c:\temp | Select-Object -Start $PSItem.CreationTime).Days}}Īs you can see in the screenshot below, there are files that are 456 days old and 492 days old. Type temp and press Enter (or click OK) to open up the folder location and see your temp files.
Using the script below, the Name, CreationTIme, and AgeInDays of each file in c:\temp is shown. In this example, there are files in c:\temp that are older than 492 days. This example is useful for removing old log files, like those generated by IIS web servers, to free up disk space.
In the third example, we will show you how to delete files using PowerShell older Than x Days. How to delete files using PowerShell older Than x Days The output should look like this screenshot below: Get-ChildItem -Path D:\temp\ -File | Remove-Item -Verbose
In the second example, using the command below you can delete multiple files in a folder using PowerShell. How to delete multiple files using PowerShell