Private/Get-AzCredential.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
      <#
      .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)
    }