PowerShell Script to Backup files & folders based on extension

Опубликовано: 01 Октябрь 2024
на канале: Fun & Tech
182
6

Use this script at your own risk to copy files from Source to Destination. Modified files will be archived.
Source and destination directories
$sourceDirectory = "C:\Path\To\Source"
$destinationDirectory = "C:\Path\To\Destination"

Get all files from the source directory
$files = Get-ChildItem -Path $sourceDirectory

foreach ($file in $files) {
Determine the destination subdirectory based on file extension
$extension = $file.Extension.TrimStart('.')
$subdirectory = Join-Path -Path $destinationDirectory -ChildPath $extension

Create the subdirectory if it doesn't exist
if (!(Test-Path -Path $subdirectory)) {
New-Item -Path $subdirectory -ItemType Directory
}

Determine the destination file path
$destinationFilePath = Join-Path -Path $subdirectory -ChildPath $file.Name

Check if the destination file already exists
if (Test-Path -Path $destinationFilePath) {
Get source and destination file last write times
$sourceLastWriteTime = $file.LastWriteTime
$destinationLastWriteTime = (Get-Item $destinationFilePath).LastWriteTime

Compare modification times for both source and destination
if ($destinationLastWriteTime -gt $sourceLastWriteTime) {
Archive the modified destination file with the current date and time
$archivePath = Join-Path -Path $subdirectory -ChildPath "Archive"
if (!(Test-Path -Path $archivePath)) {
New-Item -Path $archivePath -ItemType Directory
}
$dateSuffix = Get-Date -Format "yyyyMMdd_HHmmss"
$archiveFileName = "{0}_{1}{2}" -f $file.BaseName, $dateSuffix, $file.Extension
$archiveFilePath = Join-Path -Path $archivePath -ChildPath $archiveFileName
Move-Item -Path $destinationFilePath -Destination $archiveFilePath -Force
} elseif ($sourceLastWriteTime -gt $destinationLastWriteTime) {
Archive the modified source file with the current date and time
$archivePath = Join-Path -Path $subdirectory -ChildPath "Archive"
if (!(Test-Path -Path $archivePath)) {
New-Item -Path $archivePath -ItemType Directory
}
$dateSuffix = Get-Date -Format "yyyyMMdd_HHmmss"
$archiveFileName = "{0}_{1}{2}" -f $file.BaseName, $dateSuffix, $file.Extension
$archiveFilePath = Join-Path -Path $archivePath -ChildPath $archiveFileName
Move-Item -Path $destinationFilePath -Destination $archiveFilePath -Force
}
}

Copy the file from source to the appropriate subdirectory
Copy-Item -Path $file.FullName -Destination $destinationFilePath -Force
}