Delete Old Files Using Powershell

Today we will create a Powershell Script, which will delete your old files. You can also configure a scheduler which can delete the files automatically.

Let's start the scripting:

Step 1: Create a variable to get the old date by getting current date and subtracting the retention days:

1$cutoffDate = (Get-Date).AddDays(-5)

Step 2: Create a variable to store folder path, in which files are stored:

1$path = "C:\AutoSQLBackupScheduled"

Step 3: Lastly, get the files from the folders ,then filter the files which is less that old date variable and remove it:

1Get-ChildItem -Path $path -File | Where-Object LastWriteTime -LT $cutoffDate | Remove-Item -Force -Verbose

Now combine all three steps and save it with ".ps1" extension.

1$cutoffDate = (Get-Date).AddDays(-5)
2
3$path = "C:\testFolder"
4
5Get-ChildItem -Path $path -File | Where-Object LastWriteTime -LT $cutoffDate | Remove-Item -Force -Verbose

Now you can also configure this script to delete old files on daily basis by configurating the script in windows scheduler.

You can learn "HOW to configure Powershell script in windows Scheduler." from here..

I :heart: AWS! :smile: Enjoy