如何通过PowerShell为Azure应用授予Office SharePoint Online API权限?
Absolutely, you can grant Office SharePoint Online API permissions to an Azure AD application using PowerShell—here’s how to do it, alongside the manual steps you outlined:
Manual Steps
- Navigate to the Azure AD Admin Center
- Locate or create the application that needs the permissions
- Go to API permissions > Add a permission
- Select Office SharePoint Online from the list of APIs
- Choose Application permissions (for app-level access)
- Check the box for Sites.ReadWrite.All (matches "Read and write items in all site collections")
- Click Add permissions, then select Grant admin consent for [your tenant name] to finalize
PowerShell Method (Using Microsoft Graph SDK)
Microsoft Graph is the recommended modern approach for managing Azure AD resources. Follow these steps:
Install the Microsoft Graph module (if not already installed):
Install-Module Microsoft.Graph -Force -AllowClobberConnect to Microsoft Graph with required scopes (you’ll need admin privileges like Global Admin or Application Admin):
Connect-MgGraph -Scopes "Application.ReadWrite.All", "Directory.ReadWrite.All"Retrieve the SharePoint Online service principal (it uses a fixed app ID):
$sharePointSP = Get-MgServicePrincipal -Filter "AppId eq '00000003-0000-0ff1-ce00-000000000000'"Get your target application’s service principal:
ReplaceYourAppDisplayNamewith your app’s name (or use its App ID instead):$targetAppSP = Get-MgServicePrincipal -Filter "DisplayName eq 'YourAppDisplayName'"Identify the specific permission to assign:
$permission = $sharePointSP.AppRoles | Where-Object { $_.Value -eq "Sites.ReadWrite.All" }Assign the permission (and grant admin consent):
This command creates the assignment and automatically grants admin consent (required for application-level permissions):New-MgServicePrincipalAppRoleAssignment ` -ServicePrincipalId $targetAppSP.Id ` -PrincipalId $targetAppSP.Id ` -ResourceId $sharePointSP.Id ` -AppRoleId $permission.Id
Alternative: Using AzureAD Module (Legacy)
If you prefer the older AzureAD module, use these commands:
# Install module if needed Install-Module AzureAD -Force # Connect to Azure AD Connect-AzureAD # Get SharePoint service principal $sharePointSP = Get-AzureADServicePrincipal -Filter "AppId eq '00000003-0000-0ff1-ce00-000000000000'" # Get target app $targetAppSP = Get-AzureADServicePrincipal -Filter "DisplayName eq 'YourAppDisplayName'" # Get permission $permission = $sharePointSP.AppRoles | Where-Object { $_.Value -eq "Sites.ReadWrite.All" } # Assign permission New-AzureADServiceAppRoleAssignment ` -ObjectId $targetAppSP.ObjectId ` -PrincipalId $targetAppSP.ObjectId ` -ResourceId $sharePointSP.ObjectId ` -Id $permission.Id
Both methods achieve the exact same result as the manual workflow—assigning the required SharePoint Online API permission and granting admin consent.
内容的提问来源于stack exchange,提问作者Natalie Polishuk

