Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marckean/cfb2da2878182738aa171463f2249cff to your computer and use it in GitHub Desktop.
Save marckean/cfb2da2878182738aa171463f2249cff to your computer and use it in GitHub Desktop.
$ServicePrincipalConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
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
$VMs += Get-AzureRmVM -Status | where {$_.PowerState -eq 'VM Running'}
$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