Резервные копии

Бэкап фотографий по месяцам

Копирует изображения в папки по году и месяцу, проверяет конфликты и пишет manifest.

PowerShell Windows Новичок
Скачать Backup-Photos.ps1
Описание

Что делает скрипт

Скрипт выбирает файлы с заданными расширениями, раскладывает копии по каталогам вида 2026-05 и не перезаписывает существующие снимки. Для каждого файла считается SHA-256 и сохраняется CSV-отчёт. Поддерживается -WhatIf для предпросмотра.

Перед запуском
  • Копии занимают место, проверьте свободное пространство назначения.
Запуск

Быстрый старт

powershell -File Backup-Photos.ps1 -Source D:\Photos -Destination E:\Backup\Photos

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.

Примеры

Другие варианты

  • powershell -File Backup-Photos.ps1 -Source D:\Photos -Destination E:\Backup\Photos
  • powershell -File Backup-Photos.ps1 -Source D:\Photos -Destination E:\Backup\Photos -WhatIf
Зависимости

Что понадобится

PowerShell 5.1+ В Windows 10 и 11 уже есть PowerShell 5.1
Windows Встроен в Windows 10/11 (PowerShell 5.1)
Исходник

Backup-Photos.ps1

[CmdletBinding(SupportsShouldProcess = $true)]
param(
    [Parameter(Mandatory = $true)]
    [string]$Source,
    [Parameter(Mandatory = $true)]
    [string]$Destination,
    [string[]]$Extensions = @('.jpg', '.jpeg', '.png', '.heic', '.tif', '.tiff', '.webp', '.dng', '.cr2', '.nef', '.arw'),
    [switch]$NoHash
)

$ErrorActionPreference = 'Stop'

function Get-NormalizedPath {
    param([string]$PathValue)
    return [System.IO.Path]::GetFullPath($PathValue)
}

$sourceFull = Get-NormalizedPath $Source
$destFull = Get-NormalizedPath $Destination
$trimChars = [char[]]@('\', '/')

if (-not (Test-Path -LiteralPath $sourceFull -PathType Container)) {
    throw "Source folder not found: $sourceFull"
}
if ($destFull.TrimEnd($trimChars) -eq $sourceFull.TrimEnd($trimChars)) {
    throw 'Source and Destination must differ.'
}
if ($destFull.StartsWith($sourceFull.TrimEnd($trimChars) + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
    throw 'Destination must not be inside Source.'
}
if ($sourceFull.StartsWith($destFull.TrimEnd($trimChars) + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
    throw 'Source must not be inside Destination.'
}

$Extensions = @($Extensions | ForEach-Object { $_.ToLowerInvariant() })
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$targetRoot = Join-Path $destFull ('photos-' + $stamp)
if (Test-Path -LiteralPath $targetRoot) {
    throw "Destination already exists: $targetRoot"
}
if (-not $WhatIfPreference) {
    New-Item -ItemType Directory -Path $targetRoot -Force | Out-Null
}

$manifest = New-Object System.Collections.Generic.List[object]
$copied = 0
$skipped = 0

$files = Get-ChildItem -LiteralPath $sourceFull -Recurse -File -ErrorAction SilentlyContinue |
    Where-Object { $Extensions -contains $_.Extension.ToLowerInvariant() }

foreach ($file in $files) {
    $relative = $file.FullName.Substring($sourceFull.TrimEnd($trimChars).Length).TrimStart($trimChars)
    $parent = Split-Path -Parent $relative
    $monthFolder = $file.LastWriteTime.ToString('yyyy-MM')
    if ([string]::IsNullOrEmpty($parent)) {
        $targetDir = Join-Path $targetRoot $monthFolder
    } else {
        $targetDir = Join-Path (Join-Path $targetRoot $monthFolder) $parent
    }
    $targetName = Split-Path -Leaf $relative

    if ($PSCmdlet.ShouldProcess($file.FullName, 'Copy photo')) {
        if (-not (Test-Path -LiteralPath $targetDir -PathType Container)) {
            New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
        }
        $targetPath = Join-Path $targetDir $targetName
        $index = 1
        while (Test-Path -LiteralPath $targetPath) {
            $base = [System.IO.Path]::GetFileNameWithoutExtension($targetName)
            $extension = [System.IO.Path]::GetExtension($targetName)
            $targetPath = Join-Path $targetDir ($base + '-' + $index + $extension)
            $index++
        }
        Copy-Item -LiteralPath $file.FullName -Destination $targetPath -ErrorAction Stop
        $hash = ''
        if (-not $NoHash) {
            $hash = (Get-FileHash -LiteralPath $targetPath -Algorithm SHA256).Hash
        }
        $manifest.Add([pscustomobject]@{
            Source = $file.FullName
            Target = $targetPath
            Length = $file.Length
            Modified = $file.LastWriteTime
            SHA256 = $hash
        })
        $copied++
    } else {
        $skipped++
    }
}

if (-not $WhatIfPreference) {
    $manifestPath = Join-Path $targetRoot 'manifest.csv'
    if ($manifest.Count -gt 0) {
        $manifest | Export-Csv -LiteralPath $manifestPath -NoTypeInformation -Encoding UTF8
    } else {
        Set-Content -LiteralPath $manifestPath -Value 'Source,Target,Length,Modified,SHA256' -Encoding UTF8
    }
    Write-Host "Copied: $copied, skipped: $skipped"
    Write-Host "Manifest: $manifestPath"
} else {
    Write-Host "Preview only. Files that would be copied: $skipped"
}

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get backup-photos
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Резервные копии

Резервное копирование, синхронизация, проверка и восстановление данных.