Script to find folders in a directory and delete the folders. Can set how many folders can be left.

$path = 'E:\'

Get-ChildItem -Path $path -Directory | 
    Sort-Object LastWriteTime -Descending | 
    Select-Object -Skip 2 | 
    Remove-Item -Recurse -WhatIf

To change to delete by date created change

LastWriteTime

to

CreationTime 
Source
https://www.reddit.com/r/PowerShell/comments/45x09d/delete_all_old_backup_folders_leaving_just_two/

Categorized in:

Powershell,

Last Update: May 17, 2024