Skip to content

Instantly share code, notes, and snippets.

@ljtill
Last active October 4, 2018 21:56
Show Gist options
  • Select an option

  • Save ljtill/5a38719d4ffe67e6b421732a1326f4ad to your computer and use it in GitHub Desktop.

Select an option

Save ljtill/5a38719d4ffe67e6b421732a1326f4ad to your computer and use it in GitHub Desktop.
Provides the ability to retrieve the Access Token from the current Context
function Get-AzureRmAccessToken {
<#
.SYNOPSIS
Get-AzureRmAccessToken will retrieve the Access Token from the current AzureRm context.
.DESCRIPTION
Provides the ability to retrieve the current authenticated Access Token within the AzureRm.Profile context.
Returns the Access Token to allow for interaction directly with Microsoft Azure REST API's.
.EXAMPLE
Get-AzureRmAccessToken
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'Type')]
[ValidateSet("Current", "All")]
[string]$Type
)
begin {
Write-Verbose -Message "Initiating function 'Get-AzureRmAccessToken'."
Set-Variable -Name "Type" -Scope Private
$accessTokens = @{}
$profile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
$tenants = ""
}
process {
switch ($Type) {
"Current" {
try {
$context = Get-AzureRmContext
$client = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($Profile)
$token = $client.AcquireAccessToken($Context.Subscription.TenantId)
$accessToken = $token.AccessToken
}
catch {
Write-Error -Message $_.Exception.Message
Break
}
}
"All" {
try {
foreach ($tenant in $tenants) {
Set-AzureRmContext -Tenant $tenant | Out-Null
$context = Get-AzureRmContext
$Client = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($Profile)
$token = $client.AcquireAccessToken($context.Subscription.TenantId)
$accessToken = $Token.AccessToken
$accessTokens.Add($tenant, $accessToken)
}
} catch {
Write-Error -Message $_.Exception.Message
Break
}
}
}
}
end {
Write-Verbose -Message "Initiating function 'Get-AzureRmAccessToken' completed."
switch ($type) {
"Current" {
Return $accessToken
}
"All" {
Return $accessTokens
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment