Schedule a task to delete files older than a certain date with a specific file extension using PowerShell and task scheduler.
You are probably here because you have some amount of files in a windows directory which are taking up to much space or causing problems with your system.
Here is the quick process to setting this up.
Step 1. Open Notepad or a text editor (powershell ISE will do).
Step 2. Add the following text to your file and save it as cleanup.ps1
# set folder path $path = "C:\Users\filepath\"
# set min age of files
$max_age ="-5" # get the current date
$curr_date = Get-Date
# determine how far back we go based on current date
$del_date = $curr_date.AddDays($max_age)
# delete only .xml files which are older than 5 days
Get-ChildItem -include *.xml $path -Recurse | Where-Object { $_.LastWriteTime -lt $del_date } | Where-Object { -not ($_.psiscontainer) } | Foreach-Object {Remove-Item $_.FullName}
Step 3. Open Task Scheduler by finding it in the start menu.
Step 4. Click New Folder.
Step 5. Type any name for the folder and click OK.
Step 6. Right-click the recently created folder.
Step 7. Select Create Task.
Step 8. In the “Name” box, enter a name for the task.
Step 9. In the “General” tab, under the “Security options” section, select the Run whether user is logged on or not option. (This is the option that will make the command window not to appear when the task runs automatically.)
Step 10. Don’t check the Do not store password option.
Step 11. Go to the “Triggers” tab, and click the New button.
Step 12. Using the “Begin the task” drop-down menu, select On a schedule.
Step 13. Under “Settings,” specify when you want the task to run (e.g., On time, Daily, Weekly, Monthly). Whatever option you select, make sure to specify the Start settings on the right side.
Step 14. Click OK.
Step 15. Go to the “Actions” tab, and click the New Button.
Step 16. Using the “Actions” drop-down menu, select Start a program.
Step 17. Under “Settings,” type the following command: PowerShell.exe
Step 18. In the “Add arguments” box type the following command and click OK.
-ExecutionPolicy Bypass C:\Scripts\cleanup.ps1
Step 19. Click OK.
Step 20. Type in any necessary credentials and click OK.
Hi Anthony!!!
Great job Tony!
nice!
Thanks for the tip Anthony! Helpful as always!
Tony!!! Way to go!!