Archive and delete all files from a folder that are older than X days

$FILES = "C:\Temp\Test"
$ARCHIVE = "C:\Temp\Test\Archive"

# 30 days as an example
$TIMESPAN = (Get-Date).AddDays(-30)


# first we delete all text files (example) in the $ARCHIVE folder that are older then 30 days:
Get-ChildItem -Path ($ARCHIVE + "*.txt") | ForEach-Object{

    if($PSItem.LastWriteTime -lt $TIMESPAN)
    {
        Remove-Item $PSItem
    }

}

# now we move the files from the $FILES folder into the $ARCHIVE folder:
Get-ChildItem -Path ($FILES + "*.txt") | Move-Item -Destination $ARCHIVE
PowerShell

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *