Private/Get-AzureRmCredential.ps1

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

function Get-AzureRmCredential {
    [CmdLetBinding()]
    [Outputtype("PSCredential")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '', Justification = "There's required to convert the string to the secure string.")]
    param()
    $ErrorActionPreference = 'Stop'
    Write-Debug '-- begin - Get-AzureRmCredential --'
        
    if (-not (Get-Module AzureRm.Profile)) {
        Import-Module AzureRm.Profile
    }
            
    $azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
        
    $currentAzureContext = Get-AzureRmContext
    
    $profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile)
    
    Write-Debug ("Getting access token for tenant" + $currentAzureContext.Tenant.TenantId)
    $token = $profileClient.AcquireAccessToken($currentAzureContext.Tenant.TenantId)
    
    $securePat = ConvertTo-SecureString -String $token.UserId -AsPlainText -Force
    $Credential = New-Object System.Management.Automation.PSCredential($token.AccessToken, $securePat)
    
    Write-Debug '-- end - Get-AzureRmCredential --'
    return $Credential
}