Skip to main content

Download folder clean up

# Import the necessary namespace to work with the file system.
Add-Type -AssemblyName Microsoft.VisualBasic

# Set the source directory.
$sourcePath = "\\usr-cos\homeSTD$\ysolliard\Downloads"

# Get the current date and subtract 5 days to find the cutoff date.
$cutOffDate = (Get-Date).AddDays(-5)

# Get all files and directories in the source path.
$items = Get-ChildItem -Path $sourcePath -Recurse

# Iterate over each item.
foreach ($item in $items) {
    # Check if the item's LastWriteTime is older than the cutoff date.
    if ($item.LastWriteTime -lt $cutOffDate) {
        try {
            if ($item.PSIsContainer) {
                # If the item is a directory, move it to the Recycle Bin.
                [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory(
                    $item.FullName, 
                    [Microsoft.VisualBasic.FileIO.UIOption]::OnlyErrorDialogs, 
                    [Microsoft.VisualBasic.FileIO.RecycleOption]::SendToRecycleBin
                )
                Write-Host "Directory '$($item.FullName)' moved to Recycle Bin."
            } else {
                # If the item is a file, move it to the Recycle Bin.
                [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile(
                    $item.FullName, 
                    [Microsoft.VisualBasic.FileIO.UIOption]::OnlyErrorDialogs, 
                    [Microsoft.VisualBasic.FileIO.RecycleOption]::SendToRecycleBin
                )
                Write-Host "File '$($item.FullName)' moved to Recycle Bin."
            }
        }
        catch {
            Write-Host "Error moving item '$($item.FullName)' to Recycle Bin: $($_.Exception.Message)"
        }
    }
}