There are various ways to free up disk space on the system. On of them to delete old files which are no longer needed after a certain period of time. It can be backup files, log files, and other temporary files. This tutorial shows how to delete files older than X days on Windows.
Method 1 - CMD
The forfiles
command allows to select files and run another command on these files. Before deleting files, we can print them. For example, to find files older than 7 days run the following command:
forfiles /p "C:\Users\User\AppData\Local\Temp" /s /m *.* /d -7 /c "cmd /c echo @path"
Once confirmed, specify the del
command instead of echo
to delete files:
forfiles /p "C:\Users\User\AppData\Local\Temp" /s /m *.* /d -7 /c "cmd /c del @path"
The meaning of parameters that used in forfiles
command:
/p
- specifies the path to find files./s
- find all files in the specified directory and all subdirectories./m
- find files based on wildcard. The*.*
means to find all files regardless of the file extension./d
- find files by last modified date./c
- specifies command to run it on each file.
We can filter files by specific extension. For example, to delete .tmp
files older than 7 days run the following command:
forfiles /p "C:\Users\User\AppData\Local\Temp" /s /m *.tmp /d -7 /c "cmd /c del @path"
Method 2 - PowerShell
To find files older than 7 days run the Get-ChildItem
command in PowerShell:
Get-ChildItem "C:\Users\User\AppData\Local\Temp" -Recurse -File | Where LastWriteTime -lt (Get-Date).AddDays(-7) | %{$_.FullName}
Once confirmed, replace %{$_.FullName}
with Remove-Item -Force
to delete files:
Get-ChildItem "C:\Users\User\AppData\Local\Temp" -Recurse -File | Where LastWriteTime -lt (Get-Date).AddDays(-7) | Remove-Item -Force
Files can be filtered and deleted by specific extension as well:
Get-ChildItem "C:\Users\User\AppData\Local\Temp" -Recurse -File -Filter *.tmp | Where LastWriteTime -lt (Get-Date).AddDays(-7) | Remove-Item -Force
Leave a Comment
Cancel reply