[CmdletBinding(SupportsShouldProcess = $true)] param( [string]$Source = (Join-Path $env:USERPROFILE '.ssh'), [Parameter(Mandatory = $true)] [string]$Destination ) $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 "SSH 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 ('ssh-keys-' + $stamp) if (Test-Path -LiteralPath $targetRoot) { throw "Destination already exists: $targetRoot" } if (-not $PSCmdlet.ShouldProcess($targetRoot, 'Backup SSH keys')) { return } New-Item -ItemType Directory -Path $targetRoot -Force | Out-Null try { $acl = New-Object System.Security.AccessControl.DirectorySecurity $acl.SetAccessRuleProtection($true, $false) $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name $rule = New-Object System.Security.AccessControl.FileSystemAccessRule( $identity, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow' ) $acl.AddAccessRule($rule) Set-Acl -LiteralPath $targetRoot -AclObject $acl } catch { Write-Warning "Could not restrict ACL: $($_.Exception.Message)" } $files = Get-ChildItem -LiteralPath $sourceFull -Recurse -File -Force -ErrorAction SilentlyContinue | Where-Object { -not ($_.Attributes -band [System.IO.FileAttributes]::ReparsePoint) } $manifest = New-Object System.Collections.Generic.List[object] foreach ($file in $files) { $relative = $file.FullName.Substring($sourceFull.TrimEnd($trimChars).Length).TrimStart($trimChars) $target = Join-Path $targetRoot $relative $parent = Split-Path -Parent $target if (-not (Test-Path -LiteralPath $parent -PathType Container)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null } Copy-Item -LiteralPath $file.FullName -Destination $target -Force $manifest.Add([pscustomobject]@{ Name = $relative Length = $file.Length SHA256 = (Get-FileHash -LiteralPath $target -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 'Name,Length,SHA256' -Encoding UTF8 } Write-Warning 'Backup contains private keys. Keep it encrypted and offline.' Write-Host "Files: $($manifest.Count)" Write-Host "Folder: $targetRoot"