Skip to content

Instantly share code, notes, and snippets.

@stuartleeks
Created November 5, 2015 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartleeks/d0a0f5c7ade6e0c53643 to your computer and use it in GitHub Desktop.
Save stuartleeks/d0a0f5c7ade6e0c53643 to your computer and use it in GitHub Desktop.
Hack to get AccessToken for ARM from current PowerShell context
# Working on 1.0.0 preview of Azure PowerShell cmdlets
function GetAccessToken(){
$psContext = Get-AzureRmContext
$context = [Microsoft.Azure.Common.Authentication.Models.AzureContext] $psContext
$account = $context.Account
$environment= $context.Environment
$tenant = $context.Tenant
$authFactory = [Microsoft.Azure.Common.Authentication.AzureSession]::AuthenticationFactory
$accessToken = $authFactory.Authenticate($account, $environment, $tenant.Id, $null, "Never")
return $accessToken.AccessToken
}
function GetAuthorizationHeader(){
$token = GetAccessToken
return @{ "Authorization" = "Bearer $token"}
}
function GetSubscriptions(){
$uri = "https://management.azure.com/subscriptions?api-version=2014-04-01"
$headers = GetAuthorizationHeader
$response1 = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
$response1.value
}
function GetResourceGroups($subscriptionId){
$uri = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups?api-version=2014-04-01"
$headers = GetAuthorizationHeader
$response1 = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
$response1.value
}
$subscriptions = GetSubscriptions
$subscriptions
Write-Host ""
$resourceGroups = GetResourceGroups $subscriptions[0].subscriptionId
$resourceGroups
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment