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