Powershell: Delete a Folder of a Particular Age


image

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
    }
Advertisements

3 thoughts on “Powershell: Delete a Folder of a Particular Age

  1. Marc

    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

    Reply
  2. Jeroen Budding

    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
    }

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s