functions/azure/Get-AzStoredServicePrincipalCredential.ps1

function Get-AzStoredServicePrincipalCredential {
<#
.SYNOPSIS
Retrieves a stored service principal credential from SecretManagement.
 
.DESCRIPTION
Fetches a PSCredential object representing a service principal's credentials using Microsoft.PowerShell.SecretManagement. Supports an optional vault name if a non-default vault is used.
 
.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 to retrieve the secret from. If not specified, the default vault is used.
 
.EXAMPLE
Get-AzStoredServicePrincipalCredential -TenantId 'contoso.onmicrosoft.com' -SubscriptionId '1234-5678' -ServicePrincipalName 'my-app'
 
.EXAMPLE
Get-AzStoredServicePrincipalCredential -TenantId 'contoso.onmicrosoft.com' -SubscriptionId '1234-5678' -ServicePrincipalName 'my-app' -Vault 'MyCustomVault'
#>

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

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

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

        [string] $Vault
    )

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

    try {
        $secretParams = @{ Name = $targetName; ErrorAction = 'Stop' }
        if ($Vault) { $secretParams.Vault = $Vault }

        $credential = Get-Secret @secretParams
    }
    catch {
        Write-Error "No stored secret found for name '$targetName'."
        return
    }

    if ($credential -isnot [System.Management.Automation.PSCredential]) {
        Write-Error "The secret '$targetName' is not a PSCredential object."
        return
    }

    return [PSCustomObject]@{
        ApplicationId  = $credential.UserName
        ClientSecret   = $credential.Password
        TenantId       = $TenantId
        SubscriptionId = $SubscriptionId
        TargetName     = $targetName
        Credential     = $credential
    }
}