$ServicePrincipalConnection = Get-AutomationConnection -Name 'AzureRunAsConnection' | |
$null = Add-AzureRmAccount ` | |
-ServicePrincipal ` | |
-TenantId $ServicePrincipalConnection.TenantId ` | |
-ApplicationId $ServicePrincipalConnection.ApplicationId ` | |
-CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint | |
################################################################## | |
################################################################## | |
################################################################## | |
################################################################## | |
################################################################## | |
$Subscriptions = Get-AzureRmSubscription | |
# Get a list of VMs which are powered on, has an email address tag and has an environment tag (Dev or Test) | |
$VMs = @() | |
foreach ($Sub in $Subscriptions) { | |
$null = Select-AzureRmSubscription -Subscription $Sub | |
# Get VMs that are running and actually have a tags of some sort | |
$VMs += Get-AzureRmVM -Status | where {$_.PowerState -eq 'VM Running' -and $_.Tags.values -match '.'} | |
$VMs_with_Tags = @() | |
foreach ($VM in $VMs) { | |
$a = [psCustomObject]@{ | |
name = $VM.Name | |
CreatedBy = ($VM.Tags.Values | where {($_ -match '.@.') -and ($_ -match '.\..')}) # Find email address in a Tag | |
Environment = ($VM.Tags.Values | where {($_ -match 'dev') -or ($_ -match 'test')}) # Find environment, Dev/Test | |
} | |
$VMs_with_Tags += $a | |
} | |
} | |
# Group the VMs with tags by email address | |
$GroupedVMs_with_Tags = @() | |
($VMs_with_Tags | where {($_.CreatedBy) -or ($_.Environment)} | Group-Object CreatedBy) | % { | |
$a = [psCustomObject]@{ | |
name = $_.Name | |
VMNames = $_.Group.Name -join ', ' | |
Environment = $_.Group.Environment -join ', ' | |
} | |
$GroupedVMs_with_Tags += $a | |
} | |
$GroupedVMs_with_Tags | ConvertTo-Json -Depth 100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment