Public/Connect-KritTcm.ps1
|
function Connect-KritTcm { <# .SYNOPSIS Connect to Microsoft Graph with TCM-aware scopes. #> [CmdletBinding()] param( [string]$TenantId, [string[]]$Scopes = @('ConfigurationMonitoring.ReadWrite.All', 'Application.ReadWrite.All', 'AppRoleAssignment.ReadWrite.All'), [switch]$NoWelcome, [switch]$PassThru ) if (-not (Get-Command Connect-MgGraph -ErrorAction SilentlyContinue)) { Import-Module Microsoft.Graph.Authentication -ErrorAction Stop } $context = Get-MgContext -ErrorAction SilentlyContinue $tenantMatches = (-not $TenantId) -or ($context -and $context.TenantId -eq $TenantId) $scopeMatches = $context -and (@($Scopes | Where-Object { $_ -notin $context.Scopes }).Count -eq 0) if (-not ($tenantMatches -and $scopeMatches)) { $connectParams = @{ Scopes = $Scopes; ErrorAction = 'Stop' } if ($TenantId) { $connectParams['TenantId'] = $TenantId } if ($NoWelcome) { $connectParams['NoWelcome'] = $true } Connect-MgGraph @connectParams | Out-Null $context = Get-MgContext -ErrorAction Stop } $result = [pscustomobject]@{ Action = 'Connect-KritTcm' TenantId = $context.TenantId Account = $context.Account Scopes = @($context.Scopes) ReusedExistingConnection = [bool]($tenantMatches -and $scopeMatches) } if ($PassThru) { return $result } Write-Verbose ("Connected to tenant {0} as {1}" -f $result.TenantId, $result.Account) } |