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