Skip to content

Instantly share code, notes, and snippets.

@sjwaight
Last active February 19, 2016 03:32
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 sjwaight/d62dc371a539e6d93361 to your computer and use it in GitHub Desktop.
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.
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