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

Бэкап заметок

Копирует папку заметок в отдельный каталог, считает хеши и при желании делает zip.

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

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

Скрипт проверяет источник и назначение, использует robocopy с исключением точек повторной обработки и создаёт CSV manifest. Флаг -Zip дополнительно упаковывает копию в архив. Исходные заметки не изменяются.

Перед запуском
  • Заметки могут содержать личные данные.
Запуск

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

powershell -File Backup-Notes.ps1 -Source C:\Users\user\Documents\Notes -Destination E:\Backup\Notes

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

Примеры

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

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

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

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-Notes.ps1

[CmdletBinding(SupportsShouldProcess = $true)]
param(
    [string]$Source = (Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'Notes'),
    [Parameter(Mandatory = $true)]
    [string]$Destination,
    [switch]$Zip
)

$ErrorActionPreference = 'Stop'
$sourceFull = [System.IO.Path]::GetFullPath($Source)
$destFull = [System.IO.Path]::GetFullPath($Destination)
$trimChars = [char[]]@('\', '/')

if (-not (Test-Path -LiteralPath $sourceFull -PathType Container)) {
    throw "Notes 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.'
}

$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$targetRoot = Join-Path $destFull ('notes-' + $stamp)
if (Test-Path -LiteralPath $targetRoot) {
    throw "Destination already exists: $targetRoot"
}
if (-not $PSCmdlet.ShouldProcess($targetRoot, 'Backup notes')) {
    return
}

New-Item -ItemType Directory -Path $targetRoot -Force | Out-Null
& robocopy $sourceFull $targetRoot /E /XJ /COPY:DAT /R:1 /W:1 /NP /NFL /NDL | Out-Null
$code = $LASTEXITCODE
if ($code -ge 8) {
    throw "Robocopy failed with code $code"
}

$files = @(Get-ChildItem -LiteralPath $targetRoot -Recurse -File -Force -ErrorAction SilentlyContinue)
$manifest = New-Object System.Collections.Generic.List[object]
foreach ($file in $files) {
    $manifest.Add([pscustomobject]@{
        File = $file.FullName
        Length = $file.Length
        Modified = $file.LastWriteTime
        SHA256 = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash
    })
}

$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
}

if ($Zip) {
    if ($files.Count -eq 0) {
        Write-Warning 'Notes folder is empty, zip skipped.'
    } else {
        $zipPath = $targetRoot + '.zip'
        if (Test-Path -LiteralPath $zipPath) {
            throw "Archive already exists: $zipPath"
        }
        Compress-Archive -Path (Join-Path $targetRoot '*') -DestinationPath $zipPath -CompressionLevel Optimal
        Write-Host "Archive: $zipPath"
    }
}

Write-Host "Files: $($files.Count)"
Write-Host "Folder: $targetRoot"

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

CLI 1.0.0

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

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

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

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

Категория

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

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