Created
March 21, 2018 01:07
-
-
Save marckean/34c44d8e260e1bffeea78ae3f4427f25 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#region Install Modules | |
# Run as Administrator | |
#Find-Module AzureServicePrincipalAccount | Install-Module | |
#endregion | |
$APIResourceURI = 'https://management.core.windows.net/' # Some cases use 'https://api.loganalytics.io' | |
# Retrieve Azure Module properties | |
"" | |
"Validating installed PowerShell Version and Azure PowerShell Module version..." | |
$ReqVersions = Get-Module Azure -list | Select-Object Version, PowerShellVersion | |
# Current PowerShell version must be higher then the one required by the Azure Module | |
if($PSVersionTable.PSVersion.Major -lt $ReqVersions.PowerShellVersion.Major) | |
{ | |
$PSVerReq = $ReqVersions.PowerShellVersion | |
$PSVerInst = $PSVersionTable.PSVersion | |
"Validation failed..." | |
"Installed PowerShell version: $PSVerInst" | |
"Powershell version $PSVerReq required. Please update the version of Powershell on this system" | |
"Exiting Script" | |
Break | |
} | |
# Current script was tested with Azure module 5.0.1 | |
if($ReqVersions.Version.Major -lt 5) | |
{ | |
$AZModuleInst = $ReqVersions.Version | |
"Validation failed..." | |
"Installed Azure PS Module: $AZModuleInst. This script was tested with version 5.0.1" | |
"Please download and install/update the Azure Powershell module using the Microsoft Web Platform Installer..." | |
"Download link: https://github.com/Azure/azure-powershell/releases/tag/v5.0.1-November2017" | |
"Exiting Script" | |
Break | |
} | |
########################################################################################## | |
################## Optional AAD SP Info for un-attended sign-in ################## | |
########################################################################################## | |
# SP = Service Principal | |
$SP_Password = '' # or Certificate Thumbprint, a blank password will prompt for prompt for sign-in | |
$AADAppId = '19yf9yh923fh82hf065f8c07' | |
$TenantID = 'a8456t34t11-6a11-45d0-a439-68g34g33g437' # Directory ID | |
########################################################################################## | |
################################# Logon to Azure ################################## | |
########################################################################################## | |
switch -Wildcard ($SP_Password) | |
{ | |
?* { | |
$secpasswd = ConvertTo-SecureString $SP_Password -AsPlainText -Force | |
$Cred = New-Object System.Management.Automation.PSCredential ($AADAppId, $secpasswd) | |
Login-AzureRmAccount -Credential $cred -ServicePrincipal -TenantId $TenantId | |
} | |
default { | |
Login-AzureRmAccount | |
} | |
} | |
#region Logon to Azure & choose Azure subscription | |
$Subscription = (Get-AzureRmSubscription | Out-GridView -Title "Choose a Source & Target Subscription ..." -PassThru) | |
Select-AzureRmSubscription -Subscription $Subscription | |
$SubscriptionId = $Subscription.Id | |
#endregion | |
########################################################################################## | |
############################### AAD SP Functions ################################## | |
########################################################################################## | |
# Using logged in credentials | |
Function RestAPI-AuthToken ($TenantId, $resourceAppIdURI) { | |
# Load ADAL Azure AD Authentication Library Assemblies | |
$adal = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.dll" | |
$adalforms = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll" | |
$null = [System.Reflection.Assembly]::LoadFrom($adal) | |
$null = [System.Reflection.Assembly]::LoadFrom($adalforms) | |
$adTenant = $Subscription.TenantId | |
# Client ID for Azure PowerShell | |
$clientId = "1950a258-227b-4e31-a9cf-717495945fc2" | |
# Set redirect URI for Azure PowerShell | |
$redirectUri = "urn:ietf:wg:oauth:2.0:oob" | |
# Authenticate and Acquire Token | |
# Set Authority to Azure AD Tenant | |
$authority = "https://login.windows.net/$TenantId" | |
# Create Authentication Context tied to Azure AD Tenant | |
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority | |
# Acquire token | |
$global:Token = $authContext.AcquireToken($resourceAppIdURI, $clientId, $redirectUri, "Auto") | |
} | |
# Using AAD Application Service Principal | |
Function RestAPI-SPN-AuthToken ($TenantId, $resourceAppIdURI) { | |
$Username = $Cred.Username | |
$Password = $Cred.Password | |
# Set Authority to Azure AD Tenant | |
$authority = "https://login.windows.net/$TenantId" | |
# Build up the credentials | |
$ClientCred = [Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential]::new($UserName, $Password) | |
# Acquire token | |
$authContext = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]::new($authority) | |
$global:Token = $authContext.AcquireTokenAsync($resourceAppIdURI,$ClientCred) | |
} | |
Function SPNRequestHeader { | |
# Create Authorization Header | |
$authHeader = $global:Token.Result.CreateAuthorizationHeader() | |
# Set HTTP request headers to include Authorization header | @marckean | |
$requestHeader = @{ | |
"x-ms-version" = "2014-10-01"; #'2014-10-01' | |
"Authorization" = $authHeader | |
} | |
return $RequestHeader | |
} | |
Function RequestHeader { | |
# Create Authorization Header | |
# Set HTTP request headers to include Authorization header | @marckean | |
$requestHeader = @{ | |
"Content-Type" = "application/json"; #'2014-10-01' | |
"Authorization" = "Bearer $($global:Token.AccessToken)" | |
} | |
return $RequestHeader | |
} | |
########################################################################################## | |
################################ Rest API Token ################################## | |
########################################################################################## | |
switch -Wildcard ($SP_Password) | |
{ | |
?* { | |
RestAPI-SPN-AuthToken ($Subscription).TenantId $APIResourceURI # To Logon to Rest and get an an auth key | |
$RequestHeader = SPNRequestHeader | |
} | |
default { | |
RestAPI-AuthToken ($Subscription).TenantId $APIResourceURI | |
$RequestHeader = RequestHeader | |
} | |
} | |
$AADToken = $RequestHeader.Authorization | |
########################################################################################## | |
############################### Sample Functions ################################## | |
########################################################################################## | |
#region Function to create and post the request | |
Function Get-AzureRateCard() | |
{ | |
$method = 'GET' | |
$contentType = 'application/json' | |
# the $filter query option ONLY supports the ‘eq’ and ‘and’ logical operators at this time | |
$uri = "https://management.azure.com/subscriptions/{5}/providers/Microsoft.Commerce/RateCard?api-version={0}&`$filter=OfferDurableId eq '{1}' and Currency eq '{2}' and Locale eq '{3}' and RegionInfo eq '{4}'" -f $ApiVersion, $OfferId, $Currency, $Locale, $CountryCode, $SubscriptionId | |
$headers = @{ | |
'Authorization' = $AADToken | |
'Content-Type' = 'application/json' | |
} | |
$response = Invoke-WebRequest -Uri $uri -Method $method -ContentType $contentType -Headers $headers -UseBasicParsing | |
return $response.Content | ConvertFrom-Json | |
} | |
function Convert-Size { | |
[cmdletbinding()] | |
param( | |
[validateset("Bytes","KB","MB","GB","TB")] | |
[string]$From, | |
[validateset("Bytes","KB","MB","GB","TB")] | |
[string]$To, | |
[Parameter(Mandatory=$true)] | |
[double]$Value, | |
[int]$Precision = 4 | |
) | |
switch($From) { | |
"Bytes" {$value = $Value } | |
"KB" {$value = $Value * 1024 } | |
"MB" {$value = $Value * 1024 * 1024} | |
"GB" {$value = $Value * 1024 * 1024 * 1024} | |
"TB" {$value = $Value * 1024 * 1024 * 1024 * 1024} | |
} | |
switch ($To) { | |
"Bytes" {return $value} | |
"KB" {$Value = $Value/1KB} | |
"MB" {$Value = $Value/1MB} | |
"GB" {$Value = $Value/1GB} | |
"TB" {$Value = $Value/1TB} | |
} | |
return [Math]::Round($value,$Precision,[MidPointRounding]::AwayFromZero) | |
} | |
Function Update-AzureSearchData() | |
{ | |
$method = 'POST' | |
$contentType = 'application/json' | |
$uri = 'https://' + $SearchService + '.search.windows.net/indexes/' + ` | |
$index + '/docs/index' + '?api-version=2016-09-01' | |
$headers = @{ | |
'api-key' = $ApiKey | |
} | |
$response = Invoke-WebRequest -Uri $uri -Method $method -ContentType $contentType ` | |
-Headers $headers -Body $json -UseBasicParsing -Verbose | |
return $response.StatusCode | |
} | |
Function Get-AzureSearchData() | |
{ | |
$method = 'POST' | |
$contentType = 'application/json' | |
$uri = 'https://' + $SearchService + '.search.windows.net/indexes/' + $index + '/docs/search' + '?api-version=2016-09-01' | |
$headers = @{ | |
'api-key' = $ApiKey | |
'Accept' = 'application/json' | |
} | |
$response = Invoke-WebRequest -Uri $uri -Method $method -ContentType $contentType -Headers $headers -Body $json -UseBasicParsing | |
return ($response.Content | ConvertFrom-Json).value | |
} | |
#endregion | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment