GinShell.Azure/Public/Connect-GsAzureAccount.ps1
|
function Connect-GsAzureAccount { <# .SYNOPSIS Authenticates to Azure using a specific tenant and subscription. .DESCRIPTION Reuses an existing Az context if it matches the requested tenant/subscription. Otherwise performs browser-based interactive login. .PARAMETER TenantId Azure AD tenant ID (GUID). .PARAMETER SubscriptionId Azure subscription ID (GUID). .PARAMETER Force Force a fresh login even if a matching context already exists. .EXAMPLE Connect-GsAzureAccount -TenantId '00000000-0000-0000-0000-000000000000' -SubscriptionId '11111111-1111-1111-1111-111111111111' #> [CmdletBinding()] param ( [Parameter(Mandatory)] [ValidatePattern('^[0-9a-fA-F\-]{36}$')] [string]$TenantId, [Parameter(Mandatory)] [ValidatePattern('^[0-9a-fA-F\-]{36}$')] [string]$SubscriptionId, [switch]$Force ) try { Write-GsLog -Message "Called Connect-GsAzureAccount -TenantId '$TenantId' -SubscriptionId '$SubscriptionId' -Force:$Force" -Type Action $currentContext = Get-AzContext if ($Force) { Write-GsLog -Message "Force flag set. Initiating login..." -Type Action $out = Connect-AzAccount -Tenant $TenantId -Subscription $SubscriptionId -ErrorAction Stop Write-GsLog -Message "Connected to Azure with tenant $TenantId and subscription $SubscriptionId." -Type Info } elseif ((-not $currentContext) -or $currentContext.Tenant.Id -ne $TenantId) { Write-GsLog -Message "No matching Azure context found. Initiating login..." -Type Action $out = Connect-AzAccount -Tenant $TenantId -Subscription $SubscriptionId -ErrorAction Stop Write-GsLog -Message "Connected to Azure with tenant $TenantId and subscription $SubscriptionId." -Type Info } elseif ($currentContext.Tenant.Id -eq $TenantId -and $currentContext.Subscription.Id -ne $SubscriptionId) { Write-GsLog -Message "Correct tenant ($($currentContext.Tenant.Name)), switching subscription..." -Type Debug Set-AzContext -SubscriptionId $SubscriptionId -ErrorAction Stop $out = Get-AzContext Write-GsLog -Message "Azure subscription context switched to $SubscriptionId." -Type Info } else { Write-GsLog -Message "Azure context already matches. Reusing current session." -Type Info $out = $currentContext } Write-GsLog -Message "Azure authentication completed successfully." -Type Success return $out } catch { Write-GsLog -Message "Failed to connect or set Azure context: $($_.Exception.Message)" -Type Error throw } } |