Created
November 1, 2018 01:25
-
-
Save marckean/0993364540925d4889473e4a63a8d15a 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
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