PowerShell Script To Delete Files & Folders

Last year I wrote a blog post about how to back up the VMware vCenter Server Appliance version 6.5 via PowerShell which you can read here. It somehow slipped my mind to post another important aspect of the backup procedure and that is obviously to delete old backups since you don’t want them to hang around forever and use disk space.

The PowerShell script included in this blog post will do the following:

  • Create a log file called $logfile=””deletefiles_folders.log” in directory “D:\scripts\”. Change to your preferred location via the parameter “$logfile”. The log file will be cleaned up before the delete process starts.
  • Look for files in directory “D:\backups”. Change to your preferred location via parameter “$dir1”
    • You can add as many locations as needed, just use e.g. “$dir1”, “$dir2” and so on. Then add another “Get-ChildItem -Path” line to the script.
  • Delete backups older than 7 days but just use the “$deletefilesolderthan” parameter to specify the number of days you would like to keep the files & folders.

Copy the script below or get it from my GitHub Repository.

# PowerShell Script to delete files and or folders older than X days.
# Created by: Magnus Andersson - Sr Staff Solutions Architect @Nutanix
# Version 1.0
# ---------------------
# User input section starts here
# Define scfript log file
# Define direcroty where the vCenter Server and NSX Manager backups are located
# Define how old backups you want to remove by typing a number which corresponds to days
# User input section end here - Do not change anything below this line
# --------------------------------------------------------------------
# Delete logfile
Remove-Item $logfile
# Start delete files and or folders script
echo "----------------------------------------" >> $logfile
echo "Start deleting old backups at:" $d1 >> $logfile
Get-ChildItem -Path "$dir1" -Recurse | Where CreationTime -lt (Get-Date).AddDays(-$deletefilesolderthan) | Remove-Item -Force -Recurse *>&1 >> $logfile
echo "Finished deleting old files and or folders at:" $d2 >> $logfile



5 pings

Comments have been disabled.