LKBEN11467: Powershell script to delete files older than n days.


You need to delete files from a certain age.


An example is the daily export of databases which will fill up your hard disk.


The following script will delete files which are older than 5 days from the backup folder. Please note it writes a logfile on c:\temp. It does not create a temp folder!

Get-Date >> c:\temp\remove-old-files.log

Get-ChildItem -path "s:\backup" |Where-Object CreationTime -lt (Get-Date).AddDays(-5)|Remove-Item -WhatIf >> c:\temp\remove-old-files.log

Get-ChildItem -path "s:\backup" |Where-Object CreationTime -lt (Get-Date).AddDays(-5)|Remove-Item >> c:\temp\remove-old-files.log

If you need to delete files, you might have to enable the checkbox to run with elevated privileges!


The information provided in this document is intended for your information only. Lubby makes no claims to the validity of this information. Use of this information is at own risk!

About the Author

Author: Wim Peeters - Keskon GmbH & Co. KG

Wim Peeters is electronics engineer with an additional master in IT and over 30 years of experience, including time spent in support, development, consulting, training and database administration. Wim has worked with SQL Server since version 6.5. He has developed in C/C++, Java and C# on Windows and Linux. He writes knowledge base articles to solve IT problems and publishes them on the Lubby Knowledge Platform.

Latest update: 01/01/2021 | Comment: