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

План бэкапа и свободное место

Считает размер источников, свободное место назначения и показывает, поместится ли копия.

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

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

Скрипт обходит указанные папки, суммирует размеры файлов и сравнивает с доступным местом на диске назначения. Учитывается запас на служебные данные, результат можно сохранить в CSV. Ничего не копируется и не удаляется.

Запуск

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

powershell -File Get-BackupPlan.ps1 -Source C:\Users\user\Documents,C:\Projects -Destination E:\Backup

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

Примеры

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

  • powershell -File Get-BackupPlan.ps1 -Source C:\Users\user\Documents,C:\Projects -Destination E:\Backup
  • powershell -File Get-BackupPlan.ps1 -Source C:\Users\user\Documents -Destination E:\Backup -CsvPath E:\Backup\plan.csv
Зависимости

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

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

Get-BackupPlan.ps1

[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [string[]]$Source,
    [Parameter(Mandatory = $true)]
    [string]$Destination,
    [int]$RetentionDays = 30,
    [string]$CsvPath
)

$ErrorActionPreference = 'Stop'
$destFull = [System.IO.Path]::GetFullPath($Destination)
if (-not (Test-Path -LiteralPath $destFull -PathType Container)) {
    throw "Destination folder must exist: $destFull"
}

$rows = @()
$totalBytes = [int64]0
$totalFiles = 0

foreach ($item in $Source) {
    $full = [System.IO.Path]::GetFullPath($item)
    $count = 0
    $bytes = [int64]0
    if (Test-Path -LiteralPath $full -PathType Container) {
        $children = Get-ChildItem -LiteralPath $full -Recurse -File -Force -ErrorAction SilentlyContinue
        foreach ($file in $children) {
            if ($file.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
                continue
            }
            $count++
            $bytes += $file.Length
        }
    } elseif (Test-Path -LiteralPath $full -PathType Leaf) {
        $file = Get-Item -LiteralPath $full
        $count = 1
        $bytes = $file.Length
    } else {
        Write-Warning "Source skipped: $full"
        continue
    }

    $schedule = if ($bytes -gt 50GB) { 'weekly' } elseif ($bytes -gt 5GB) { 'daily' } else { 'daily or on change' }
    $rows += [pscustomobject]@{
        Source = $full
        Files = $count
        SizeGB = [math]::Round($bytes / 1GB, 2)
        Suggested = $schedule
    }
    $totalBytes += $bytes
    $totalFiles += $count
}

$freeBytes = $null
$root = [System.IO.Path]::GetPathRoot($destFull)
if ($root -match '^([A-Za-z]):') {
    $drive = Get-PSDrive -Name $Matches[1] -ErrorAction SilentlyContinue
    if ($drive -and $null -ne $drive.Free) {
        $freeBytes = [int64]$drive.Free
    }
} else {
    Write-Warning 'Destination is not on a local drive letter, free space is unknown.'
}

$neededBytes = [int64]($totalBytes * 1.15)
$rows | Format-Table -AutoSize

Write-Host ("Files: {0}, source size: {1} GB" -f $totalFiles, [math]::Round($totalBytes / 1GB, 2))
Write-Host ("Planned copy with overhead: {0} GB" -f [math]::Round($neededBytes / 1GB, 2))
if ($null -ne $freeBytes) {
    Write-Host ("Free space: {0} GB" -f [math]::Round($freeBytes / 1GB, 2))
    if ($freeBytes -lt $neededBytes) {
        Write-Warning 'Not enough free space for one full copy.'
    } else {
        Write-Host 'There is enough free space for one full copy.'
    }
}
Write-Host ("Retention: {0} days" -f $RetentionDays)

if (-not [string]::IsNullOrWhiteSpace($CsvPath)) {
    $csvFull = [System.IO.Path]::GetFullPath($CsvPath)
    if (Test-Path -LiteralPath $csvFull) {
        throw "CSV already exists: $csvFull"
    }
    $rows | Export-Csv -LiteralPath $csvFull -NoTypeInformation -Encoding UTF8
    Write-Host "CSV: $csvFull"
}

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

CLI 1.0.0

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

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

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

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

Категория

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

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