Private/Get-AzureRmCredential.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
31
      <#
      .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")]
        $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
    }