Two cool things Powershell does is Sort easily and also has -WhatIf for testing. If the Powershell version is v3 or higher, you can use -Directory versus the PSIsContainer logic:
$files = Get-ChildItem C:\Websites -Directory | Select Name, CreationTime, FullName | Sort CreationTime $files for ($i=0;$i -lt ($files.Count -2);$i++) { Remove-Item $files[$i].FullName -WhatIf } Name CreationTime FullName —- ———— ——– Ver3 7/13/2014 9:31:14 AM C:\Websites\Ver3 Ver1 8/14/2014 9:22:50 AM C:\Websites\Ver1 Ver2 8/14/2014 9:22:58 AM C:\Websites\Ver2 Ver4 8/14/2014 9:23:17 AM C:\Websites\Ver4 Ver5 8/14/2014 9:43:40 AM C:\Websites\Ver5 What if: Performing the operation "Remove Directory" on target "C:\Websites\Ver3". What if: Performing the operation "Remove Directory" on target "C:\Websites\Ver1". What if: Performing the operation "Remove Directory" on target "C:\Websites\Ver2".
You can even manipulate the CreationTime of files\folders for amusement:
(Get-Item C:\Websites\Ver5).CreationTime = (Get-Date).AddDays(-54)