Skip to content

Instantly share code, notes, and snippets.

PS> Connect-AzAccount
PS> $app = Register-MyGraphApp -DisplayName "MyVeryProductiveGraphApp"
PS> $app
ClientId TenantId
-------- --------
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
PS> Connect-MgGraph -ClientId $app.ClientId -TenantId $app.TenantId
function Register-MyGraphApp {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]
$DisplayName
)
$requiredModules = @("Az.Accounts", "Az.Resources")
foreach ($module in $requiredModules) {
$isLoaded = Get-Module -Name $module
if ($isLoaded) {
Write-Verbose -Message "$($module) module is loaded."
} else {
Write-Error -Message "$($module) module is not loaded, please install by 'Install-Module $($module)'."
}
}
[PSCustomObject]@{
ClientId = $app.AppId
TenantId = (Get-AzContext).Tenant.Id
}
$spForApp = Get-AzADServicePrincipal -ApplicationId $app.AppId
if (-not ($spForApp)) {
$spForApp = New-AzADServicePrincipal -ApplicationId $app.AppId
foreach ($permission in $requiredPermissions) {
Add-AzADAppPermission -ObjectId $app.Id -ApiId $apiId -PermissionId $permission
}
Write-Verbose -Message "Azure Service Principal created: $($spForApp.Id)"
} else {
Write-Verbose -Message "Service Principal already exists"
}
$app = Get-AzADApplication -DisplayName $displayName
if (-not ($app)) {
Write-Verbose -Message "Azure Application was not found. Creating..."
$params = @{
DisplayName = $displayName
SignInAudience = "AzureADMyOrg"
IsFallbackPublicClient = $true
}
$app = New-AzADApplication @params
Write-Verbose -Message "Azure Application created: $($app.AppId)"
$displayName = "My Microsoft Graph App"
$apiId = "00000003-0000-0000-c000-000000000000" # Microsoft Graph
$requiredPermissions = @(
"a154be20-db9c-4678-8ab7-66f6cc099a59", # (User.Read.All)
"aec28ec7-4d02-4e8c-b864-50163aea77eb" # (UserAuthenticationMethod.Read.All)
)
# list delegated permissions
(Get-AzADServicePrincipal -DisplayName "Microsoft Graph").Oauth2PermissionScope |
Select-Object Id, Value, AdminConsentDisplayName
# list application permissions
(Get-AzADServicePrincipal -DisplayName "Microsoft Graph").AppRole |
Select-Object Id, Value, DisplayName
Get-AzADAppPermission -ObjectId <object_id> |
Foreach-Object {
$permissionId = $_.Id
(Get-AzADServicePrincipal -DisplayName "Microsoft Graph").Oauth2PermissionScope |
Where-Object { $_.Id -eq $permissionId }
} | Select-Object Id, Value, AdminConsentDisplayName
# replace object_id with the 'Object ID' of your app registration
Get-AzADAppPermission -ObjectId <object_id>