GinShell.Azure/Public/Connect-GsAzureAccount.ps1

function Connect-GsAzureAccount {
    param (
        [Parameter(Mandatory = $true)]
        [string]$TenantId,

        [Parameter(Mandatory = $true)]
        [string]$SubscriptionId,
        [switch]$Force
    )

    try {
        Write-GsLog -Message "Called func Connect-GsAzureAccount -TenantId '$TenantId' -SubscriptionId '$SubscriptionId' -Force '$Force'" -Type Action

        $currentContext = Get-AzContext
        if ($Force) {
            Write-GsLog -Message "Forcefully. 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 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 "Authenticated with correct tenant ($($currentContext.Tenant.Name)), but using a different subscription ($($currentContext.Subscription.Name))." -Type Debug
            Write-GsLog -Message "Switching Azure subscription to $SubscriptionId..." -Type Action
            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 the specified tenant and subscription. Reusing current session." -Type Info
        }
        Write-GsLog -Message "Successfully completed the azure authentication process." -Type Success
        return $out
    }
    catch {
        Write-GsLog -Message "Failed to connect or set Azure context: $($_.Exception.Message)" -Type Error
        exit 1
    }
}