Automatically Archive Old Files with PowerShell

In this post, we will provide a PowerShell script that automates the process of archiving files that haven’t been modified for a specified period. Keeping your directories organized is crucial for optimizing storage and improving system performance. This script allows you to move old files to an archive folder based on your criteria, streamlining your file management process.
Here is the PowerShell script for archiving old files:

# Define the source directory and archive directory
$sourceDir = "C:\YourSourceDirectory"  # Specify your source directory
$archiveDir = "C:\YourArchiveDirectory"  # Specify your archive directory
$daysThreshold = 30  # Number of days to consider a file as old
# Create the archive directory if it does not exist
if (-not (Test-Path -Path $archiveDir)) {
    New-Item -ItemType Directory -Path $archiveDir
}
# Get the current date and calculate the cutoff date
$currentDate = Get-Date
$cutoffDate = $currentDate.AddDays(-$daysThreshold)
# Find and move old files to the archive directory
Get-ChildItem -Path $sourceDir -File | Where-Object { $_.LastWriteTime -lt $cutoffDate } | ForEach-Object {
    Move-Item -Path $_.FullName -Destination $archiveDir
    Write-Host "Archived file: $($_.FullName) to $archiveDir"
}
Write-Host "Archiving old files completed successfully."