Private/Get-AzCredential.ps1

      <#
      .SYNOPSIS
          Helper to get Credentials based on connect into Azure when Az.Accounts is installed
      .DESCRIPTION
          Helper to get Credentials based on connect into Azure when Az.Accounts is installed
      #>

      function Get-AzCredential {
        [CmdLetBinding()]
        [Outputtype("PSCredential")]
        $ErrorActionPreference = 'Stop'
        Write-Debug '-- begin - Get-AzCredential --'
    
        if (-not (Get-Module Az.Accounts)) {
            Import-Module Az.Accounts
        }

        $azProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
          
        $currentAzureContext = Get-AzContext
        $profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azProfile)
    
        Write-Debug ("Getting access token for tenant" + $currentAzureContext.Tenant.TenantId)
        $token = $profileClient.AcquireAccessToken($currentAzureContext.Tenant.TenantId)
    
        $securePat = ConvertTo-SecureString -String $currentAzureContext.Account.Id -AsPlainText -Force
        $Credential = New-Object System.Management.Automation.PSCredential($token.AccessToken, $securePat)
    
        Write-Debug '-- end - Get-AzCredential --'
        return ($Credential)
    }