functions/azure/Add-ApplicationPermission.ps1

function Add-ApplicationPermission {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [Alias('AppId')]
        [guid]$ClientId,

        [Parameter(Mandatory = $true)]
        [string[]]$ScopeNames
    )

    $graphSpId = Get-MicrosoftGraphServicePrincipalId
    $availableScopes = Get-MicrosoftGraphPermissions -OAuth2PermissionScopes -MicrosoftGraphServicePrincipalId $graphSpId

    $matchedScopes = @()
    foreach ($scopeName in $ScopeNames) {
        $scope = $availableScopes | Where-Object { $_.value -eq $scopeName }
        if (-not $scope) {
            Write-Error "Scope '$scopeName' not found!"
            return $false
        }
        $matchedScopes += $scope
    }

    $headers = @{
        Authorization  = Get-RequestHeaderAuthorization -RequestUri 'https://graph.microsoft.com'
        "Content-Type" = "application/json"
    }

    # Bestehende Grants prüfen
    $existingGrantsUri = "https://graph.microsoft.com/v1.0/oauth2PermissionGrants?`$filter=clientId eq '$ClientId' and resourceId eq '$graphSpId'"
    $existingGrant = Invoke-RestMethod -Method GET -Uri $existingGrantsUri -Headers $headers

    if ($existingGrant.value.Count -gt 0) {
        # Bereits existierender Grant -> Scopes ggf. erweitern
        $currentScopes = $existingGrant.value[0].scope -split ' '
        $newScopes = ($currentScopes + $matchedScopes.value) | Sort-Object -Unique
        $scopeString = ($newScopes -join ' ')

        $grantId = $existingGrant.value[0].id
        $patchPayload = @{
            scope = $scopeString
        } | ConvertTo-Json

        Write-Verbose "Updating existing OAuth2PermissionGrant with scopes: $scopeString"
        Invoke-RestMethod -Method PATCH -Uri "https://graph.microsoft.com/v1.0/oauth2PermissionGrants/$grantId" -Headers $headers -Body $patchPayload
    }
    else {
        # Neuer Grant
        $scopeString = ($matchedScopes.value -join ' ')
        $payload = @{
            clientId    = $ClientId
            consentType = "AllPrincipals"
            principalId = $null
            resourceId  = $graphSpId
            scope       = $scopeString
        } | ConvertTo-Json -Depth 3

        Write-Verbose "Creating new OAuth2PermissionGrant with scopes: $scopeString"
        Invoke-RestMethod -Method POST -Uri "https://graph.microsoft.com/v1.0/oauth2PermissionGrants" -Headers $headers -Body $payload
    }

    return $true
}