+4 votes
254 views
How to delete files from X days ago with PowerShell command

in Windows Server by (552k points)
reopened | 254 views

1 Answer

+5 votes
Best answer

There are many tasks that we can carry out using Windows PowerShell in Windows being of all kinds, networks, users, disks, etc., but one that perhaps very little we use is the possibility of deleting files that have been created in a period of time , this is practical when tasks that store large amounts of data , such as logs or logs, are created and executed within our team, and this gradually fills the disk space and in reality little or nothing we access it..

Windows PowerShell gives us the possibility to delete these files and today in TechnoWikis we will see how to delete these files in a simple and functional way.

For this we have the following data:

image

We can see in the column Creation date various dates, PowerShell is responsible for comparing these creation dates and delete the files that are based on the condition that we indicate..

Step 1

To perform this task we will carry out the execution of this deletion, we will access Windows PowerShell as administrators and we will execute the following syntax:
 Get-ChildItem -Path "Route" -Recurse | Where-Object CreationTime -LT (Get-Date) .AddDays (-10) | Remove-Item 
Step 2

This cmdlet is composed of the following:
Get-ChildItem
List the files in the selected folder.
-Path
It refers to the path where the files to be deleted are located.
-Recurse
Get the details of those files.
Where-Objetc
Objects with the assigned creation date will be deleted.
-LT (Get-Date)
Execute an action, in this case you get the creation date.
AddDays
We specify the number of days, that is, files with dates less than this will be deleted.
Remove-Item
Delete the files.
Step 3

In this example we will delete the files that were created 10 days before the current date: image
Step 4

We can see the change produced:
Before deletion
image
After deletion
image

We can see that the file or files that were created before these ten days have been deleted.

If we wish, we can add this script in the task scheduler so that this action is automatically carried out and thus free up disk space..


by (3.5m points)
edited

Related questions

+4 votes
1 answer
+3 votes
1 answer
asked Mar 23, 2021 in Office by backtothefuture (552k points) | 417 views
+4 votes
1 answer
+4 votes
1 answer
asked Jan 27, 2021 in Xbox by backtothefuture (552k points) | 186 views
+3 votes
1 answer
asked Oct 23, 2019 in Linux / Unix by backtothefuture (552k points) | 318 views
Sponsored articles cost $40 per post. You can contact us via Feedback

Most popular questions within the last 30 days

10,659 questions
10,791 answers
510 comments
3 users