Last active
February 19, 2016 03:32
-
-
Save sjwaight/d62dc371a539e6d93361 to your computer and use it in GitHub Desktop.
Shows how we can use a Service Principal identity in an Azure Automation Runbook.
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=$false)] | |
[String]$AzureCredentialAssetName = "VMPowerServicePrincipal", | |
[Parameter(Mandatory=$false)] | |
[String]$AzureSubscriptionIDAssetName = "VMShutdownTargetSubscription", | |
[Parameter(Mandatory=$false)] | |
[String]$AzureTenantIDAssetName = "VMShutdownTargetTenant" | |
) | |
# Setting error and warning action preferences | |
$ErrorActionPreference = "SilentlyContinue" | |
$WarningPreference = "SilentlyContinue" | |
# Read in Creds and Variables | |
$TenantId = Get-AutomationVariable -Name $AzureTenantIDAssetName | |
$Cred = Get-AutomationPSCredential -Name $AzureCredentialAssetName -ErrorAction Stop | |
$SubsciptionId = Get-AutomationVariable -Name $AzureSubscriptionIDAssetName | |
# Connecting to Azure using Service Principal | |
$null = Login-AzureRmAccount -ServicePrincipal -Tenant $TenantId -SubscriptionId $SubsciptionId -Credential $Cred -ErrorAction Stop | |
# Read all VMs in the current Subscription | |
$vmList = Get-AzureRmVM | |
$stoppedVMCount = 0 | |
# Iterate over each VM to get detailed status | |
foreach($vmEntry in $vmList) | |
{ | |
# get the power state of the VM | |
$vmDetail = Get-AzureRmVM -Name $vmEntry.Name -ResourceGroupName $vmEntry.ResourceGRoupName -Status -WarningAction $WarningPreference -ErrorAction $ErrorActionPreference | |
# If this string is present then the VM is on. | |
if($vmDetail.StatusesText.Contains("PowerState/running")) | |
{ | |
Stop-AzureRmVM -Name $vmDetail.Name -ResourceGroupName $vmDetail.ResourceGRoupName -Force -WarningAction $WarningPreference -ErrorAction $ErrorActionPreference | |
$stoppedVMCount++ | |
} | |
} | |
Write-Output "Stopped $($stoppedVMCount) Virtual Machine(s)." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment