Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
[String] $VMnames
$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)
foreach ($Sub in $Subscriptions) {
$null = Select-AzureRmSubscription -Subscription $Sub
# Filter out the VMs for the current subscription
$SubVMs = @()
# Get all Azure VMs based ont eh current Azure subscription
$AzureVMs = Get-AzureRmVM
# Do a foreach against all the VMs provided in parameter - some aren't in the current subscription
foreach($a in ($VMnames -split ', ')){
# Check if the current VM in the parameter array exists in the current Azure subscription
if($a -in ${
$b = Get-AzureRmVM | ? {$_.Name -eq $a}
$c = [psCustomObject]@{
name = $b.Name
ResourceGroupName = $b.ResourceGroupName
$SubVMs += $c
Write-Output $SubVMs
ForEach ($VM in $SubVMs)
Stop-AzureRmVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName -Force
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment