Копировать файлы с проверкой
Копирует дерево файлов в другую папку, сверяет SHA-256 и переключается на цель только после успешной проверки.
Что делает скрипт
Скрипт повторяет относительную структуру каталогов, копирует каждый файл во временное имя и сравнивает хеш источника и копии. Только после совпадения временный файл переименовывается в целевой. По умолчанию печатается план, для копирования нужен -Apply.
- С -Overwrite существующие файлы в приёмнике будут заменены после успешной проверки.
Быстрый старт
powershell -File Copy-Verify.ps1 -Source D:\Photos -Destination E:\Backup\Photos
Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.
Другие варианты
powershell -File Copy-Verify.ps1 -Source D:\Photos -Destination E:\Backup\Photospowershell -File Copy-Verify.ps1 -Source D:\Docs -Destination E:\Docs -Apply
Что понадобится
Встроен в Windows 10/11 (PowerShell 5.1)
Copy-Verify.ps1
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Source,
[Parameter(Mandatory = $true)]
[string]$Destination,
[string]$Filter = '*',
[switch]$Apply,
[switch]$Overwrite
)
$ErrorActionPreference = 'Stop'
if (-not (Test-Path -LiteralPath $Source -PathType Container)) {
throw "Source folder not found: $Source"
}
$sourceRoot = (Resolve-Path -LiteralPath $Source).Path
$destinationRoot = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Destination)
if ($destinationRoot -eq $sourceRoot) {
throw 'Destination must differ from source.'
}
$separator = [System.IO.Path]::DirectorySeparatorChar
if ($destinationRoot.StartsWith($sourceRoot + $separator, [System.StringComparison]::OrdinalIgnoreCase)) {
throw 'Destination must not be inside source.'
}
$files = @(Get-ChildItem -LiteralPath $sourceRoot -File -Recurse -Filter $Filter -ErrorAction SilentlyContinue)
if ($files.Count -eq 0) {
Write-Host 'No files found.'
exit 0
}
$copied = 0
$skipped = 0
$failed = 0
foreach ($file in $files) {
$relative = $file.FullName.Substring($sourceRoot.Length).TrimStart([char[]]@('\', '/'))
$target = Join-Path -Path $destinationRoot -ChildPath $relative
if ((Test-Path -LiteralPath $target) -and (-not $Overwrite)) {
Write-Host "Skip, target exists: $relative"
$skipped++
continue
}
if (-not $Apply) {
Write-Host "Preview: $relative"
continue
}
$parent = Split-Path -Parent $target
if (-not (Test-Path -LiteralPath $parent -PathType Container)) {
[System.IO.Directory]::CreateDirectory($parent) | Out-Null
}
$temp = Join-Path -Path $parent -ChildPath ('.copyverify-' + [guid]::NewGuid().ToString('N'))
try {
Copy-Item -LiteralPath $file.FullName -Destination $temp -ErrorAction Stop
$sourceHash = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash
$targetHash = (Get-FileHash -LiteralPath $temp -Algorithm SHA256).Hash
if ($sourceHash -ne $targetHash) {
throw "Hash mismatch: $relative"
}
Move-Item -LiteralPath $temp -Destination $target -Force:$Overwrite -ErrorAction Stop
Write-Host "Copied and verified: $relative"
$copied++
} catch {
Write-Host "ERROR: $($_.Exception.Message)" -ForegroundColor Red
$failed++
if (Test-Path -LiteralPath $temp) {
Remove-Item -LiteralPath $temp -Force -ErrorAction SilentlyContinue
}
}
}
if (-not $Apply) {
Write-Host "Preview: $($files.Count) file(s). Add -Apply to copy and verify."
} else {
Write-Host "Copied: $copied, skipped: $skipped, failed: $failed"
}
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.