Skip to content

Instantly share code, notes, and snippets.

@svarukala
Last active February 9, 2021 06:43
Show Gist options
  • Save svarukala/09a35eb344f998cc09ec029b5086d406 to your computer and use it in GitHub Desktop.
Save svarukala/09a35eb344f998cc09ec029b5086d406 to your computer and use it in GitHub Desktop.
Enumerate the lists from a SPO site using Microsoft Graph and app-only permissions on a Azure AD application
clear
# Application (client) ID, secret, tenant name and site
$tenantPrefix = "CONTOSO"; #Pass 'Contoso' for contoso.onmicrosoft.com
$clientId = "CLIENT ID"; #Pass the azure ad app id here
$clientSecret = "CLIENT SECRET"; #Pass the azure ad app client secret
$tenantName = $tenantPrefix +".onmicrosoft.com";
$tenantDomain = $tenantPrefix +".sharepoint.com";
$sitePath = "https://contoso.sharepoint.com/sites/Web01"
$siteName = $sitePath.Split("/")[4]
$resource = "https://graph.microsoft.com/"
$ReqTokenBody = @{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
client_Id = $clientID
Client_Secret = $clientSecret
}
$TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody
$AccessToken = $TokenResponse.access_token
$apiUrl = 'https://graph.microsoft.com/v1.0/sites/'+ $tenantDomain +':/sites/'+ $siteName +'?$select=id,displayName'
try {
$spoResult = Invoke-RestMethod -Headers @{Authorization = "Bearer $($Tokenresponse.access_token)"} -Uri $apiUrl -Method Get
Write-Host "Site: " $spoResult.displayName
}
catch {
Write-Output "Failed to enumerate the site"
Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__
#Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription
Exit
}
$apiUrl = 'https://graph.microsoft.com/v1.0/sites/'+ $spoResult.id +'/lists?$select=displayName'
try {
$spoData = Invoke-RestMethod -Headers @{Authorization = "Bearer $($Tokenresponse.access_token)"} -Uri $apiUrl -Method Get -ContentType "text/plain" -ResponseHeadersVariable spoRespHeaders
$spoData.Value | FT
}
catch {
Write-Output "Failed to add permissions the site"
Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__
Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment