az role assignment create --assignee <`appId`> --role <Role> --scope <resource URI>
下列 CLI 範例會將 Reader 角色指派給 rg-001 資源群組中所有資源的服務主體:
az role assignment create --assignee 0a123b56-c987-1234-abcd-1a2b3c4d5e6f --role Reader --scope '\/subscriptions/a1234bcd-5849-4a5d-a2eb-5267eae1bbc7/resourceGroups/rg-001'
$subscriptionId = "{azure-subscription-id}"
$resourceGroupName = "{resource-group-name}"
# Authenticate to a specific Azure subscription.
Connect-AzAccount -SubscriptionId $subscriptionId
# Password for the service principal
$pwd = "{service-principal-password}"
$secureStringPassword = ConvertTo-SecureString -String $pwd -AsPlainText -Force
# Create a new Azure Active Directory application
$azureAdApplication = New-AzADApplication `
-DisplayName "My Azure Monitor" `
-HomePage "https://localhost/azure-monitor" `
-IdentifierUris "https://localhost/azure-monitor" `
-Password $secureStringPassword
# Create a new service principal associated with the designated application
New-AzADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId
# Assign Reader role to the newly created service principal
New-AzRoleAssignment -RoleDefinitionName Reader `
-ServicePrincipalName $azureAdApplication.ApplicationId.Guid