functions/azure/Remove-AzStoredServicePrincipalCredential.ps1

function Remove-AzStoredServicePrincipalCredential {
<#
.SYNOPSIS
Removes a stored service principal credential from a SecretManagement vault.
 
.DESCRIPTION
Deletes a previously stored PSCredential secret for a service principal from the default or specified vault.
 
.PARAMETER TenantId
The Azure Active Directory tenant ID.
 
.PARAMETER SubscriptionId
The Azure subscription ID.
 
.PARAMETER ServicePrincipalName
The name of the service principal.
 
.PARAMETER Vault
(Optional) The name of the SecretManagement vault from which to remove the secret. If not specified, the default vault is used.
 
.EXAMPLE
Remove-AzStoredServicePrincipalCredential -TenantId 'contoso.onmicrosoft.com' -SubscriptionId '1234-5678' -ServicePrincipalName 'my-app'
 
.EXAMPLE
Remove-AzStoredServicePrincipalCredential -TenantId 'contoso.onmicrosoft.com' -SubscriptionId '1234-5678' -ServicePrincipalName 'my-app' -Vault 'MyCustomVault'
#>

    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(Mandatory = $true)]
        [string] $TenantId,

        [Parameter(Mandatory = $true)]
        [string] $SubscriptionId,

        [Parameter(Mandatory = $true)]
        [string] $ServicePrincipalName,

        [string] $Vault
    )

    $targetName = "$TenantId-$SubscriptionId-$ServicePrincipalName"

    $params = @{ Name = $targetName }
    if ($Vault) { $params.Vault = $Vault }

    if ($PSCmdlet.ShouldProcess($targetName, "Remove service principal credential")) {
        try {
            Remove-Secret @params
        }
        catch {
            Write-Warning "Could not remove secret '$targetName'. It may not exist or an error occurred: $_"
        }
    }
}