Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save moiaune/4cb187039fcb3ac6b1447cd1a157fc24 to your computer and use it in GitHub Desktop.
Save moiaune/4cb187039fcb3ac6b1447cd1a157fc24 to your computer and use it in GitHub Desktop.
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)'."
}
}
$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)
)
$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)"
} else {
Write-Verbose -Message ("App Registration {0} already exists" -f $DisplayName)
}
$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"
}
[PSCustomObject]@{
ClientId = $app.AppId
TenantId = (Get-AzContext).Tenant.Id
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment