[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" }