public/Connect-MyCorp.ps1
|
function Connect-MyCorp { <# .SYNOPSIS Connect to Microsoft 365 services (Graph, Azure, Exchange Online, Teams). .DESCRIPTION Connects to Graph/Azure/Exchange/Teams. After Azure login it enumerates subscriptions and stores them in the MyCorp session. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'Color output intended')] [Alias('Connect-MyCorpGraph', 'Connect-MtMyCorp')] [CmdletBinding()] param( [switch] $SendMail, [switch] $SendTeamsMessage, [switch] $Privileged, [switch] $UseDeviceCode, [ValidateSet('China', 'Germany', 'Global', 'USGov', 'USGovDoD')] [string]$Environment = 'Global', [ValidateSet('AzureChinaCloud', 'AzureCloud', 'AzureUSGovernment')] [string]$AzureEnvironment = 'AzureCloud', [ValidateSet('O365China', 'O365Default', 'O365GermanyCloud', 'O365USGovDoD', 'O365USGovGCCHigh')] [string]$ExchangeEnvironmentName = 'O365Default', [ValidateSet('TeamsChina', 'TeamsGCCH', 'TeamsDOD')] [string]$TeamsEnvironmentName = $null, [ValidateSet('All', 'Azure', 'ExchangeOnline', 'Graph', 'SecurityCompliance', 'Teams')] [string[]]$Service = 'Graph', [string]$TenantId ) # Ensure session variable exists if (-not (Test-Path variable:\__MyCorpSession)) { New-Variable -Name __MyCorpSession -Value ([PSCustomObject]@{ Connections=@(); Subscriptions=@(); SelectedSubscription=$null; DefaultSubscription=$null; MyCorpConfig=$null }) -Scope Script -Force | Out-Null } $__MyCorpSession.Connections = $Service $OrderedImport = Get-ModuleImportOrder -Name @('Az.Accounts', 'ExchangeOnlineManagement', 'Microsoft.Graph.Authentication', 'MicrosoftTeams') switch ($OrderedImport.Name) { 'Az.Accounts' { if ($Service -contains 'Azure' -or $Service -contains 'All') { Write-Verbose 'Connecting to Microsoft Azure' try { # Enumerate Azure subscriptions and store in session try { $subs = Get-AzSubscription -ErrorAction Stop | Select-Object Id, Name, TenantId, State $__MyCorpSession.Subscriptions = $subs if ($subs.Count -eq 0) { Write-Verbose 'No Azure subscriptions found for the signed-in account.' } elseif ($subs.Count -eq 1) { $__MyCorpSession.DefaultSubscription = $subs[0] $__MyCorpSession.SelectedSubscription = $subs[0] # Set context automatically Set-AzContext -SubscriptionId $subs[0].Id -ErrorAction SilentlyContinue Write-Verbose "Using single subscription: $($subs[0].Name) ($($subs[0].Id))" } else { Write-Verbose "Discovered $($subs.Count) Azure subscriptions. Use Select-MyCorpSubscription to choose which subscription to run tests against." Write-Host "Available Azure Subscriptions:" -ForegroundColor Yellow $index = 0 foreach ($s in $subs) { $index++ Write-Host ("[{0}] {1} ({2})" -f $index, $s.Name, $s.Id) } # DO NOT autoselect — user must select manually } } catch { Write-Warning "Failed to enumerate Azure subscriptions: $($_.Exception.Message)" $__MyCorpSession.Subscriptions = @() } } catch [Management.Automation.CommandNotFoundException] { Write-Host "`nAzure PowerShell module not installed." -ForegroundColor Red Write-Host "Install-Module Az.Accounts -Scope CurrentUser`n" -ForegroundColor Yellow } catch { Write-Warning "Azure login failed: $($_.Exception.Message)" } } } 'ExchangeOnlineManagement' { # existing Exchange connection logic (unchanged)... if ($Service -contains 'ExchangeOnline' -or $Service -contains 'All') { Write-Verbose 'Connecting to Exchange Online' try { if ($UseDeviceCode -and $PSVersionTable.PSEdition -eq 'Desktop') { Write-Host 'Exchange Online PowerShell in Windows PowerShell does not support device code flow.' -ForegroundColor Red Write-Host 'Use PowerShell Core for device code login.' -ForegroundColor Yellow } elseif ($UseDeviceCode) { Connect-ExchangeOnline -ShowBanner:$false -Device:$UseDeviceCode -ExchangeEnvironmentName $ExchangeEnvironmentName } else { Connect-ExchangeOnline -ShowBanner:$false -ExchangeEnvironmentName $ExchangeEnvironmentName } } catch [Management.Automation.CommandNotFoundException] { Write-Host "`nExchange Online module missing." -ForegroundColor Red Write-Host "Install-Module ExchangeOnlineManagement -Scope CurrentUser`n" -ForegroundColor Yellow } catch { Write-Warning "Exchange connect failed: $($_.Exception.Message)" } } # Security & Compliance block unchanged... } 'Microsoft.Graph.Authentication' { if ($Service -contains 'Graph' -or $Service -contains 'All') { Write-Verbose 'Connecting to Microsoft Graph' try { $scopes = Get-MtGraphScope -SendMail:$SendMail -SendTeamsMessage:$SendTeamsMessage -Privileged:$Privileged $connectParams = @{ Scopes = $scopes; NoWelcome = $true; UseDeviceCode = $UseDeviceCode; Environment = $Environment } if ($TenantId) { $connectParams['TenantId'] = $TenantId } Connect-MgGraph @connectParams if (-not $TenantId) { $TenantId = (Get-MgContext).TenantId } } catch [Management.Automation.CommandNotFoundException] { Write-Host "`nMicrosoft Graph module missing." -ForegroundColor Red Write-Host "Install-Module Microsoft.Graph.Authentication -Scope CurrentUser`n" -ForegroundColor Yellow } catch { Write-Warning "Graph connect failed: $($_.Exception.Message)" } } } 'MicrosoftTeams' { if ($Service -contains 'Teams' -or $Service -contains 'All') { Write-Verbose 'Connecting to Microsoft Teams' try { if ($UseDeviceCode) { Connect-MicrosoftTeams -UseDeviceAuthentication } elseif ($TeamsEnvironmentName) { Connect-MicrosoftTeams -TeamsEnvironmentName $TeamsEnvironmentName > $null } else { Connect-MicrosoftTeams > $null } } catch [Management.Automation.CommandNotFoundException] { Write-Host "`nMicrosoft Teams module missing." -ForegroundColor Red Write-Host "Install-Module MicrosoftTeams -Scope CurrentUser`n" -ForegroundColor Yellow } catch { Write-Warning "Teams connect failed: $($_.Exception.Message)" } } } } # end switch OrderedImport } # end function Connect-MyCorp |