Private/Remove-SshImportIdAuthorizedKey.ps1
|
function Remove-SshImportIdAuthorizedKey { <# .SYNOPSIS Removes keys tagged with a given ssh-import-id identity from an authorized_keys file. #> [CmdletBinding(SupportsShouldProcess)] [OutputType([pscustomobject])] param( [Parameter(Mandatory)] [string] $Path, [Parameter(Mandatory)] [string] $Tag ) if (-not (Test-Path -Path $Path)) { return [pscustomobject]@{ Removed = @() } } $lines = @(Get-Content -Path $Path -ErrorAction SilentlyContinue) $suffix = "# ssh-import-id $Tag" $toRemove = @() $toKeep = @() foreach ($line in $lines) { if ($line.TrimEnd().EndsWith($suffix, [StringComparison]::Ordinal)) { $toRemove += $line } else { $toKeep += $line } } $removed = @() if ($toRemove.Count -gt 0 -and $PSCmdlet.ShouldProcess($Path, "Remove $($toRemove.Count) key(s) tagged '$Tag'")) { Set-Content -Path $Path -Value $toKeep $removed = $toRemove } [pscustomobject]@{ Removed = $removed } } |