Created
November 2, 2015 19:33
-
-
Save eosfor/9c51ea9ec66c114ce947 to your computer and use it in GitHub Desktop.
getAzureObject
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
<# | |
# Load ADAL 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" | |
[System.Reflection.Assembly]::LoadFrom($adal) | |
[System.Reflection.Assembly]::LoadFrom($adalforms) | |
#> | |
function Get-AzureObject { | |
[CmdletBinding()] | |
param( | |
[Parameter(Mandatory=$true)] | |
[string[]]$Name, | |
[Parameter(Mandatory = $false)] | |
[string]$SubscriptionName, | |
$apiVersion = '2014-04-01-preview', | |
[Parameter()] | |
[switch]$VMOnly, | |
[switch]$ServiceOnly, | |
[switch]$StorageOnly, | |
[switch]$All, | |
[Parameter(Mandatory=$false, HelpMessage = 'Returns raw data, works faster')] | |
[switch]$RawOutput, | |
$ADTenant = "yourADTenantNameHere.onmicrosoft.com", | |
$authHeader | |
) | |
begin{ | |
if (! $PSBoundParameters["authHeader"]) {$authHeader = Get-AzureAuthHeader -ADTenant $ADTenant} | |
## hashtable with resource types and actions for each type | |
$typesToFilter = @{'Microsoft.ClassicCompute/virtualMachines' = {param($id, $rg, $n) Get-AzureVM -SubscriptionName (Get-AzureSubscription -SubscriptionId $id).SubscriptionName -ServiceName $rg -Name $n}; | |
'Microsoft.ClassicCompute/domainNames' = {param($id, $rg, $n) Get-AzureService -SubscriptionName (Get-AzureSubscription -SubscriptionId $id).SubscriptionName -ServiceName $rg}; | |
'microsoft.classicstorage/storageaccounts' = {param($id, $rg, $n) getStorageAccount $id $rg $n}} | |
## query string to include all subscriptions registered by using Add-AzureAccount (subscriptions part of the query) | |
$subscrFilterString = ?: {$PSBoundParameters['SubscriptionName']} {generateFilterStringForSubscription -SubscriptionName $SubscriptionName} {generateFilterStringForSubscription} | |
$headers = @{"x-ms-version"="$headerDate"; | |
"Authorization" = $authHeader; | |
'Accept' = 'application/json'} | |
# API method | |
$method = "GET" | |
#defaultFilter | |
$foundFilterString = @() # | |
} | |
process{ | |
## by default function runs a query for all objects and after that it filters out the | |
## resulting set by just removing unnecessary stuff | |
## REST filter | |
## prepare set of filters to remove unnecessary stuff afterwards | |
if ($VMOnly.IsPresent){ | |
$foundFilterString += "(`$_.type -eq 'Microsoft.ClassicCompute/virtualMachines')" | |
} | |
elseif ($ServiceOnly.IsPresent){ | |
$foundFilterString += "(`$_.type -eq 'Microsoft.ClassicCompute/domainNames')" | |
} | |
elseif ($StorageOnly.IsPresent){ | |
$foundFilterString += "(`$_.type -eq 'microsoft.classicstorage/storageaccounts')" | |
} | |
else { | |
$foundFilterString = $typesToFilter.Keys | % {"(`$_.type -eq '$_')"} | |
} | |
## build filter string for REST Query call | |
$objectFilter = ($Name | %{ ("substringof('$_',name)", "substringof('$_',resourcegroup)") -join " or " }) -join " or " | |
## query header (name part of the filter) | |
$headers.'x-ms-path-query' = "/resources?api-version=$apiVersion&`$filter=($subscrFilterString) and ($objectFilter)" | |
# generate the API URI | |
$URI = "https://management.azure.com/api/invoke" | |
# execute the Azure REST API | |
$list = Invoke-RestMethod -Uri $URI -Method $method -Headers $headers -ErrorAction stop | |
## parse received objects | |
$objectsFound = | |
$list.value | %{ | |
$element = $_ | |
$r = [regex]::Match($element.id, "/subscriptions/(?<SubscriptionID>.+)/resourceGroups/(?<ResourceGroup>.+?)/.+/(?<ObjectName>.+)$") | |
new-object psobject -Property @{SubscriptionID = $r.Groups["SubscriptionID"]; ResourceGroup = $r.Groups["ResourceGroup"]; ObjectName = $element.name; type = $element.type; location = $element.location} | |
} | |
## remove unnecessary results | |
$resultingFilterStr = ($foundFilterString -join " -or ") | |
write-verbose $resultingFilterStr | |
$foundFilter = [scriptblock]::Create($resultingFilterStr) | |
$filteredObjects = $objectsFound | where $foundFilter | |
if (! $all.IsPresent){ | |
## if -All is set return all objects | |
$filteredObjects = $filteredObjects | where ObjectName -in $Name | |
} | |
if ($RawOutput.IsPresent) {$filteredObjects; return} | |
## query objects using classic cmdlets based on filtered results | |
$filteredObjects | % {& $typesToFilter[$_.type] $_.SubscriptionID $_.ResourceGroup $_.ObjectName} | |
} | |
} | |
function Get-AzureAuthHeader { | |
[CmdletBinding()] | |
param($ADTenant = "yourADTenantNameHere.onmicrosoft.com") | |
Write-Verbose "Getting auth header" | |
# Set well-known client ID for AzurePowerShell | |
$clientId = "1950a258-227b-4e31-a9cf-717495945fc2" | |
# Set redirect URI for Azure PowerShell | |
$redirectUri = "urn:ietf:wg:oauth:2.0:oob" | |
# Set Resource URI to Azure Service Management API | |
$resourceAppIdURI = "https://management.core.windows.net/" | |
# Set Authority to Azure AD Tenant | |
$authority = "https://login.windows.net/$ADTenant" | |
# Create Authentication Context tied to Azure AD Tenant | |
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority | |
# Acquire token | |
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $redirectUri, "Auto") | |
# API header | |
$headerDate = '2014-10-01' | |
$authHeader = $authResult.CreateAuthorizationHeader() | |
$authHeader | |
} | |
function generateFilterStringForName{ | |
[CmdletBinding()] | |
param($Name, [switch]$VMOnly, [switch]$ServiceOnly, [switch]$StorageOnly) | |
$nameFilterString = | |
($Name | % { | |
$current = $_ | |
if ($VMOnly.IsPresent) {"substringof('$current',name)"} | |
elseif ($ServiceOnly.IsPresent) {"substringof('$current',resourcegroup)"} | |
elseif ($StorageOnly.IsPresent) {"substringof('$current',name)"} | |
else {("substringof('$current',name)", "substringof('$current',resourcegroup)", "substringof('$current',name)")} | |
}) -join " or " | |
write-verbose "Names filter`: $nameFilterString" | |
$nameFilterString | |
} | |
function generateFilterStringForSubscription{ | |
[CmdletBinding()] | |
param($SubscriptionName) | |
if ($PSBoundParameters['SubscriptionName']){ | |
$subscriptions = (Get-AzureSubscription -SubscriptionName $SubscriptionName).SubscriptionId | |
} | |
else { | |
$subscriptions = (Get-AzureSubscription).SubscriptionId | |
} | |
$subscrFilterString = ($subscriptions | % {"subscriptionId eq '$_'"}) -join ' or ' | |
write-verbose "Subscriptions filter`: $subscrFilterString" | |
$subscrFilterString | |
} | |
function getStorageAccount { | |
param($id, $rg, $n) | |
$sub = Get-AzureSubscription -SubscriptionId $id | |
$acct = Get-AzureStorageAccount -StorageAccountName $n -SubscriptionName $sub.SubscriptionName 3> $null | |
$acct | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment