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


This article has not been checked!

LKB | Created: 16/12/2020 | Version: 2 | Language: EN | Rating: 0 | Outdated: False | Marked for deletion: False

Author: Wim Peeters - Keskon GmbH & Co. KG

Latest update: 01/01/2021 | Comment:


Symptom

You need to delete files from a certain age.

Cause

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

Solution

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!

About the Author

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.

Disclaimer:

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!