File Archiving Script
In this post, we will share a PowerShell script that automates the archiving of older files in a specified directory. This script helps you keep your workspace organized by moving files that are no longer actively needed to an archive folder.
For those interested in advanced server management capabilities, we encourage you to explore our software, ServerEngine, at https://serverengine.co. Lets break down the script into manageable steps.
### Step 1: Define Source and Archive Directories
The first step is to define the source directory containing the files to be archived and the destination directory where the archived files will be moved.
$sourceDirectory = 'C:\FilesToArchive' $archiveDirectory = 'D:\ArchivedFiles' $daysThreshold = 30 $thresholdDate = (Get-Date).AddDays(-$daysThreshold)
### Step 2: Create Archive Directory
Next, we need to ensure that the archive directory exists. If it doesnt, the script will create the directory to ensure a proper destination for archived files.
if (-Not (Test-Path -Path $archiveDirectory)) { New-Item -ItemType Directory -Path $archiveDirectory Write-Host "Created archive directory: $archiveDirectory" }
### Step 3: Identify and Move Old Files
Now, we will search for files in the source directory that are older than the specified threshold. These files will be moved to the archive directory to keep the main directory uncluttered.
Get-ChildItem -Path $sourceDirectory -File | Where-Object { $_.LastWriteTime -lt $thresholdDate } | ForEach-Object { Move-Item -Path $_.FullName -Destination $archiveDirectory Write-Host "Archived: $($_.Name) to $archiveDirectory" }
### Step 4: Summary of Archived Files
Finally, we will provide a summary that tells the user how many files were archived, giving clear feedback on the operation’s success.
$archivedFilesCount = (Get-ChildItem -Path $archiveDirectory -File).Count Write-Host "Archiving process completed. $archivedFilesCount files were moved to '$archiveDirectory'."
Feel free to customize the paths and the days threshold according to your needs. This script is an excellent way to keep your directories organized and your important files safe! Continue visiting our website for more useful PowerShell scripts.