Share via

PowerShell script to utilize GraphAPI to generate Azure service principal and get all sharepoint lists

Anonymous
2025-03-07T19:01:03+00:00

I need a PowerShell script to utilize GraphAPI to generate Azure service principal and get all sharepoint lists

Microsoft 365 and Office | SharePoint | For business | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Anonymous
2025-03-07T19:20:49+00:00

Dear VS120810

Step 1:

To Register a Microsoft Entra app and create a service principal follow article: https://learn.microsoft.com/en-us/entra/identity-platform/howto-create-service-principal-portal or below PS:

 Install AzureAD or Microsoft Graph module if not installed

 Install-Module AzureAD -Scope CurrentUser

 Install-Module Microsoft.Graph -Scope CurrentUser

# Connect to Azure AD

Connect-AzureAD

# Define application details

$AppName = "GraphAP_Test"

$HomePage = "https://myenterpriseapp.com"

$ReplyURLs = @("https://localhost")  # Add necessary reply URLs

# Register a new Azure AD Enterprise Application

$App = New-AzureADApplication -DisplayName $AppName -Homepage $HomePage -ReplyUrls $ReplyURLs -AvailableToOtherTenants $false

$AppId = $App.AppId

Write-Host "Application ID (Client ID): $AppId"

# Create a Service Principal for the application

$ServicePrincipal = New-AzureADServicePrincipal -AppId $AppId

Write-Host "Service Principal Created: $($ServicePrincipal.ObjectId)"

# Generate a Client Secret

$PasswordCredential = New-AzureADApplicationPasswordCredential -ObjectId $App.ObjectId -CustomKeyIdentifier "ClientSecret"

$ClientSecret = $PasswordCredential.Value

Write-Host "Client Secret: $ClientSecret"

# Get Tenant ID

$TenantId = (Get-AzureADTenantDetail).ObjectId

Write-Host "Tenant ID: $TenantId"

# Assign Graph API Permissions for SharePoint (Sites.FullControl.All)

$graphPermissions = @(

    "Sites.FullControl.All",     # Full Control over all SharePoint sites

    "Sites.Manage.All",          # Manage SharePoint sites

    "Sites.Read.All",            # Read SharePoint sites

    "Sites.ReadWrite.All"        # Read/Write SharePoint sites

)

# Assign API permissions

$GraphAppId = "00000003-0000-0000-c000-000000000000" # Microsoft Graph API App ID

foreach ($perm in $graphPermissions) {

    $AppRole = Get-AzureADServicePrincipal -Filter "AppId eq '$GraphAppId'" | Select-Object -ExpandProperty AppRoles | Where-Object {$_.Value -eq $perm}

    if ($AppRole) {

        New-AzureADServiceAppRoleAssignment -ObjectId $ServicePrincipal.ObjectId -PrincipalId $ServicePrincipal.ObjectId -ResourceId (Get-AzureADServicePrincipal -Filter "AppId eq '$GraphAppId'").ObjectId -Id $AppRole.Id

        Write-Host "Assigned permission: $perm"

    } else {

        Write-Host "Permission $perm not found"

    }

}

Write-Host "Azure AD Enterprise App Created Successfully!"

Write-Host "Client ID: $AppId"

Write-Host "Client Secret: $ClientSecret"

Write-Host "Tenant ID: $TenantId"

Above Script will display ClientID, ClientS, Tenant ID

Step 2:

Get SharePoint site ID-> Go to URL https://developer.microsoft.com/en-us/graph/graph-explorer

Sign In to the graph portal -> Modify the site->Run Query->Copy SiteID

Graph Query: GET https://graph.microsoft.com/v1.0/sites/contoso.sharepoint.com:/sites/TS

**Step 3:**Now finally **** GraphAPI Script to list SharePoint list/Library, Modify line 2,3,4 and 27 from above outputs:

# Define parameters

$TenantId = "

$ClientId = "

$ClientSecret = "

$Scope = "https://graph.microsoft.com/.default"

$TokenEndpoint = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"

# Request Access Token

$Body = @{

    client_id     = $ClientId

    client_secret = $ClientSecret

    scope         = $Scope

    grant_type    = "client_credentials"

}

$Response = Invoke-RestMethod -Uri $TokenEndpoint -Method Post -Body $Body -ContentType "application/x-www-form-urlencoded"

$AccessToken = $Response.access_token

if (-not $AccessToken) {

    Write-Host "Failed to retrieve access token!" -ForegroundColor Red

    exit

}

Write-Host "Access token retrieved successfully." -ForegroundColor Green

# Hardcoded SharePoint Site ID (Replace with actual Site ID)

$SiteID = "

# Set Headers

$Headers = @{

    Authorization = "Bearer $AccessToken"

    "Content-Type" = "application/json"

}

# Fetch SharePoint Site Details

$GraphUri = "https://graph.microsoft.com/v1.0/sites/$SiteID"

try {

    $SiteResponse = Invoke-RestMethod -Uri $GraphUri -Headers $Headers -Method Get

    Write-Host "Successfully connected to SharePoint site: $($SiteResponse.displayName)" -ForegroundColor Cyan

    Write-Host "Site ID: $($SiteResponse.id)"

    Write-Host "Web URL: $($SiteResponse.webUrl)"

} catch {

    Write-Host "Failed to retrieve site details. Check permissions & site ID." -ForegroundColor Red

    Write-Host $_.Exception.Message

    exit

}

# Fetch Document Libraries

$GraphUriLibraries = "https://graph.microsoft.com/v1.0/sites/$SiteID/drives"

try {

    $LibrariesResponse = Invoke-RestMethod -Uri $GraphUriLibraries -Headers $Headers -Method Get

    if ($LibrariesResponse.value) {

        Write-Host "Document Libraries in the Site:" -ForegroundColor Cyan

        $LibrariesResponse.value | Select-Object name, id | Format-Table -AutoSize

    } else {

        Write-Host "No libraries found or insufficient permissions." -ForegroundColor Yellow

    }

} catch {

    Write-Host "Failed to retrieve document libraries. Check permissions & Site ID." -ForegroundColor Red

    Write-Host $_.Exception.Message

}

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

0 additional answers

Sort by: Most helpful