functions/azure/Set-AzStoredServicePrincipalCredential.ps1

function Set-AzStoredServicePrincipalCredential {
<#
.SYNOPSIS
Stores a service principal credential using SecretManagement.
 
.DESCRIPTION
Stores a PSCredential object representing a service principal's application ID and client secret in a SecretManagement vault. 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 ApplicationId
The application ID (client ID) of the service principal.
 
.PARAMETER ClientSecret
The client secret of the service principal, as a SecureString or String.
 
.PARAMETER Vault
(Optional) The name of the SecretManagement vault to store the secret in. If not specified, the default vault is used.
 
.EXAMPLE
Set-AzStoredServicePrincipalCredential -TenantId 'contoso.onmicrosoft.com' -SubscriptionId '1234-5678' -ServicePrincipalName 'my-app' -ApplicationId 'appid-guid' -ClientSecret (Read-Host -AsSecureString)
 
.EXAMPLE
Set-AzStoredServicePrincipalCredential -TenantId 'contoso.onmicrosoft.com' -SubscriptionId '1234-5678' -ServicePrincipalName 'my-app' -ApplicationId 'appid-guid' -ClientSecret $secureSecret -Vault 'MyCustomVault'
#>

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

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

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

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

        [Parameter(Mandatory = $true)]
        [Object] $ClientSecret,

        [string] $Vault
    )

    if ($ClientSecret -is [string]) {
        try {
            $secureSecret = ConvertTo-SecureString -String $ClientSecret -AsPlainText -Force
        } catch {
            throw "ClientSecret konnte nicht in SecureString konvertiert werden: $_"
        }
    } elseif ($ClientSecret -is [SecureString]) {
        $secureSecret = $ClientSecret
    } else {
        throw "ClientSecret muss entweder ein String oder SecureString sein."
    }

    $targetName = "$TenantId-$SubscriptionId-$ServicePrincipalName"
    $credential = New-Object System.Management.Automation.PSCredential($ApplicationId, $secureSecret)

    $setParams = @{ 
        Name = $targetName
        Secret = $credential
    }
    if (-not ([string]::IsNullOrWhiteSpace($Vault))) { { $setParams += @{ Vault = $Vault } } }

    if ($PSCmdlet.ShouldProcess($targetName, "Store service principal credentials")) {
        Set-Secret @setParams
    }
}