Powershell, Azure Management API & Password Grant Type - example

This example uses PowerShell and REST for connecting to the Azure Management API for managing the cloud platform.

This example uses the Password grant type (Username and Password) for connecting to Azure.

$AccountName    = "testuser@mytenant.onmicrosoft.com"
$Password       = "Password"
$TenantID       = "mytenant.onmicrosoft.com"
$SubscriptionId = "2be53ae5-6e46-47df-beb9-6f3a795387b8"


# Constants

$ClientId       = "1950a258-227b-4e31-a9cf-717495945fc2"
$AzureResourceURI = "https://login.microsoftonline.com/$($tenantID)/oauth2/token"
$AzureResourceID  = "https://management.azure.com/"

$Body = "grant_type=password"`
         +"&username=" +$AccountName`
         +"&client_id=" +$clientId`
         +"&scope=openid"`
         +"&password=" +$Password`
         +"&resource=" +[system.uri]::EscapeDataString($AzureResourceID)

$Response = Invoke-WebRequest -Uri $AzureResourceURI -Method POST -Body $Body
$ResponseJSON = $Response|ConvertFrom-Json

$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("Authorization", "Bearer "+$ResponseJSON.access_token)
$Headers.Add("Content-Type", "application/json")

# This example will use the Azure management endpoint to
# Create a Resource Group
#

$ResourceGroupName     = "ResourceGroup4"
$ResourceGroupLocation = "Australia SouthEast"

$uri = "https://management.azure.com/subscriptions/$($subscriptionid)/resourcegroups/"`
     +"$($ResourceGroupName)?api-version=2018-05-01"

$body= @"
{
  "location": "$($ResourceGroupLocation)"
}
"@

$response = Invoke-WebRequest -Uri $uri -Method PUT -Headers $Headers -Body $body
$response.StatusDescription