Last active
November 3, 2018 05:47
-
-
Save marckean/58f0bbecd60aebf37635908368d90de0 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
$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