ScriptsWindows Server

Task Scheduler – PowerShell – Clean Drive

Create Task Scheduler and Clean drive using PowerShell Script

1- Prepare your PS Script, and save it

# PowerShell Script to clean all files in D:\ older than 1 day.
# Schedule: Daily, 01:00:00 PT, 08:00:00 UTC

# Directory path to wipe. Root of D:\ in this case.
$dir1="D:\"

# Max allowable age of files before we delete it (in days)
$deletefilesolderthan="1"

# Exceptions - do not delete if name matches
$exception = "DATALOSS_WARNING_README.txt"

# Look at all surface-level items, delete if older than max age.
# But exclude the dataloss warning file.
Get-ChildItem -Path "$dir1" -Recurse -exclude "$exception"| 
    Where CreationTime -lt (Get-Date).AddDays(-$deletefilesolderthan) | 
    Remove-Item -Force -Recurse

 

2- Create Task Scheduler

  • Open Task Scheduler
  • Right Click, and create New folder
  • Name it CleanDrive
  • Click on CleanDrive, then right click to create Basic Task
  • Name your Tasks
  • Select your schedule
  • Choose Start a Program
  • In Program Script type: PowrShell
  • Add Argurment: -ExectionPolicy Bypass -File C:\filelocation
  • Click Finish

 

Show More

Related Articles

Back to top button