Entra / Microsoft 365 · Applications
Get Graph permissions for a script
Parse a script block, list Microsoft Graph PowerShell SDK commands it uses, and report the Graph permissions each command requires.
Connect & set up
Run these once per session. All scopes are read-only unless the script makes changes.
# Review required modules and connection steps before running.# Connect to Microsoft Graph or Exchange Online as needed for this script.
Run it
The main script. Copy it, or download the .ps1 and run it from your console.
function Get-GraphScriptPermission {[CmdletBinding()]param ([Parameter(Mandatory = $true, Position = 0)][scriptblock] $Script)begin {$ast = [System.Management.Automation.Language.Parser]::ParseInput($Script.ToString(), [ref]$null, [ref]$null)[array]$commandElementList = $null# Extract a list of command elements and their associated parameters from the AST[array]$CommandElementList = $ast.FindAll({$args[0].GetType().Name -like 'CommandAst'}, $true) | ForEach-Object {[pscustomobject]@{Cmdlet = $Cmdlet = $_.CommandElements[0].ValueSource = (Get-Command -Name $Cmdlet).SourceVerb = (Get-Command -Name $Cmdlet).VerbType = (Get-Command -Name $Cmdlet).NounAllPrivileges = $null}}}process {$GraphScopeReport = [System.Collections.Generic.List[Object]]::new()[array]$CommandList = $CommandElementList | Where-Object Source -like 'Microsoft.Graph*'ForEach ($GraphCommand in $CommandList) {[array]$ScopeOutput = $null[array]$Scopes = (Find-MgGraphCommand -Command $GraphCommand.Cmdlet | `Select-Object -ExpandProperty Permissions | Sort-Object Name, isAdmin -Unique)ForEach ($Scope in $Scopes) {$ScopeInfo = ("{0} (admin: {1})" -f $Scope.Name, $Scope.isAdmin)[array]$ScopeOutput += $ScopeInfo}[string]$ScopeOutput = $ScopeOutput -Join ", "$DataLine = [PSCustomObject][Ordered]@{Cmdlet = $GraphCommand.cmdletSource = $GraphCommand.SourceVerb = $GraphCommand.VerbType = $GraphCommand.TypeScopes = $ScopeOutput}$GraphScopeReport.Add($DataLine)}$GraphScopeReport | Sort-Object Cmdlet -Unique}end {}}# Original version from https://gist.github.com/HCRitter/d7017ce1eeb66689b14a108423d383ab. See# https://www.linkedin.com/pulse/get-graphscriptpermission-christian-ritter-gsaie/ for more information.# Amended in several places to make the list of scopes a string rather than an array
Attribution
Author
Office365itpros