Powershell Aficionado

Delete Folders older than X days Recursively

Everyone runs into the problem eventually  where they need to delete folders based on age. The script discussed in this post does exactly that. It checks the passed folder, or the default if no folder is specified and if there are any folders under it that are more than X days old, the folder and it's contents are removed.

To understand where a script like this may be useful, see our article, Error 0x00000002 when Adding a printer.

Delete Folders..., the Script;

param (
  [string]$path = "C:\Windows\system32\spool\prtprocs\w32x86\",
  [Int]$olderthan = 7,
  [bool]$testmode = $true
  )

$limit = (Get-Date).AddDays(-$olderthan)

if(-Not $testmode){
   write-warning "Running in non-test mode"
   }
else{
     write-warning "Running in test mode, use -notest=true to override"
     Get-ChildItem -Path $path | Where-Object {
      ($_.PSIsContainer -and $_.LastWriteTime -lt $limit) 
      } | Remove-Item -Force -Recurse -whatif
 }

Overview

There are three parameters that can be given.

  1. path, the path to the folder on which the script will operate. This can be a local path or a full unc path.
    • default: C:\Windows\system32\spool\prtprocs\w32x86\.
  2. olderthan, folders older than this many days will be deleted from the system.
    • default: 7
  3. testmode, if true, then the -whatif parameter is also used, meaning the folders will not be deleted. Use -testmode $false to really delete the folders.

 

 

Leave a Reply