I created this script to delete a folder which is older than two days. I needed this for a simple backup solution. I have a Powershell script that will backup a VM which runs in VMware Workstation. This script runs everyday and creates a folder with a date stamp. After a couple weeks there where a lot of copies of the particular VM and the free space of the backup hard disk became very low.
This script will remove all folders in the D:\vmbackup folder which are older then 2 days.
$Now = Get-Date $Days = "2" $TargetFolder = "D:\vmbackup" $LastWrite = $Now.AddDays(-$Days) $Folders = get-childitem -path $TargetFolder | Where {$_.psIsContainer -eq $true} | Where {$_.LastWriteTime -le "$LastWrite"} foreach ($Folder in $Folders) { write-host "Deleting $Folder" -foregroundcolor "Red" Remove-Item $Folder -recurse -Confirm:$false }
Don’t know why it did not work with my environment, I got the error cannot find path c:\folder (where folder is a subfolder of $targetfolder).
I changed your script to this:
$folder = $targetfolder + “\” + $folder
write-host “Deleting $Folder” -foregroundcolor “Red”
Remove-Item $Folder -recurse -Confirm:$false
and now it worked…
thx
Hey – tried using this code and the additional comment code but had various problems. I’ve resolved them and you can see the final code here on the MS Powershell forums: http://social.technet.microsoft.com/Forums/en-ca/winserverpowershell/thread/ca1d2077-42d1-4110-8fc1-78d21affb7a5
Following script needs to be changed.
I changed the Remove-Item so it goes to the correct directory.
$Now = Get-Date
$Days = “30”
$TargetFolder = “D:\Report”
$LastWrite = $Now.AddDays(-$Days)
$Folders = get-childitem -path $TargetFolder |
Where {$_.psIsContainer -eq $true} |
Where {$_.LastWriteTime -le “$LastWrite”}
foreach ($Folder in $Folders)
{
write-host “Deleting $Folder” -foregroundcolor “Red”
Remove-Item $TargetFolder\$Folder -recurse -Confirm:$false
}