Skip to content

Instantly share code, notes, and snippets.

@marckean
Created November 1, 2018 01:25
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/0993364540925d4889473e4a63a8d15a to your computer and use it in GitHub Desktop.
Save marckean/0993364540925d4889473e4a63a8d15a to your computer and use it in GitHub Desktop.
param
(
[parameter(Mandatory=$true)]
[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 $AzureVMs.name){
$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