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

Бэкап документов Windows

Копирует документы и рабочий стол в папку с меткой времени и считает хеши файлов.

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

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

Скрипт проверяет источники, запрещает вложенные пути и использует robocopy с исключением точек повторной обработки. После копирования создаётся CSV manifest с размерами и SHA-256. Поддерживается -WhatIf, чтобы увидеть запуск без записи.

Перед запуском
  • Проверьте, что в документы не попали временные и личные файлы.
Запуск

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

powershell -File Backup-Documents.ps1 -Destination E:\Backup\Documents

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

Примеры

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

  • powershell -File Backup-Documents.ps1 -Destination E:\Backup\Documents
  • powershell -File Backup-Documents.ps1 -Source C:\Users\user\Documents -Destination E:\Backup\Documents -WhatIf
Зависимости

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

PowerShell 5.1+ В Windows 10 и 11 уже есть PowerShell 5.1
Windows Встроен в Windows 10/11 (PowerShell 5.1)
Windows 10/11 Robocopy, certutil, reg.exe и PowerShell входят в систему
Windows Встроено в Windows 10/11
Исходник

Backup-Documents.ps1

[CmdletBinding(SupportsShouldProcess = $true)]
param(
    [string[]]$Source = @(
        [Environment]::GetFolderPath('MyDocuments'),
        [Environment]::GetFolderPath('Desktop')
    ),
    [Parameter(Mandatory = $true)]
    [string]$Destination,
    [switch]$NoHash
)

$ErrorActionPreference = 'Stop'
$destFull = [System.IO.Path]::GetFullPath($Destination)
$trimChars = [char[]]@('\', '/')
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$targetRoot = Join-Path $destFull ('documents-' + $stamp)

$sources = @()
foreach ($item in $Source) {
    if ([string]::IsNullOrWhiteSpace($item)) { continue }
    $full = [System.IO.Path]::GetFullPath($item)
    if (Test-Path -LiteralPath $full -PathType Container) {
        $sources += $full
    }
}
if ($sources.Count -eq 0) {
    throw 'No source folders found.'
}

foreach ($sourceFull in $sources) {
    if ($destFull.TrimEnd($trimChars) -eq $sourceFull.TrimEnd($trimChars)) {
        throw "Source and destination must differ: $sourceFull"
    }
    if ($destFull.StartsWith($sourceFull.TrimEnd($trimChars) + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
        throw "Destination must not be inside source: $sourceFull"
    }
    if ($sourceFull.StartsWith($destFull.TrimEnd($trimChars) + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
        throw "Source must not be inside destination: $sourceFull"
    }
}

if (Test-Path -LiteralPath $targetRoot) {
    throw "Destination already exists: $targetRoot"
}
if (-not $PSCmdlet.ShouldProcess($targetRoot, 'Backup documents')) {
    return
}

New-Item -ItemType Directory -Path $targetRoot -Force | Out-Null
$manifest = New-Object System.Collections.Generic.List[object]
$total = 0

foreach ($sourceFull in $sources) {
    $name = Split-Path -Leaf $sourceFull
    $target = Join-Path $targetRoot $name
    $index = 1
    while (Test-Path -LiteralPath $target) {
        $target = Join-Path $targetRoot ($name + '-' + $index)
        $index++
    }
    New-Item -ItemType Directory -Path $target -Force | Out-Null
    & robocopy $sourceFull $target /E /XJ /COPY:DAT /R:1 /W:1 /NP /NFL /NDL | Out-Null
    $code = $LASTEXITCODE
    if ($code -ge 8) {
        throw "Robocopy failed for $sourceFull with code $code"
    }
    $files = @(Get-ChildItem -LiteralPath $target -Recurse -File -Force -ErrorAction SilentlyContinue)
    foreach ($file in $files) {
        $hash = ''
        if (-not $NoHash) {
            $hash = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash
        }
        $manifest.Add([pscustomobject]@{
            File = $file.FullName
            Length = $file.Length
            Modified = $file.LastWriteTime
            SHA256 = $hash
        })
        $total++
    }
}

$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 'File,Length,Modified,SHA256' -Encoding UTF8
}
Write-Host "Files: $total"
Write-Host "Folder: $targetRoot"

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

CLI 1.0.0

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

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

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

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

Категория

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

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