Azure provides an abundance of services tailored to ease the workload of IT professionals. One such remarkable service is Azure Functions, which allows you to run scripts or pieces of code in response to a variety of events. Today, we’ll explore how to leverage Azure Functions to run a PowerShell script that automates the restart of Azure AVDs based on a tag.
Understanding the Script
Before diving into Azure Functions, let’s understand the provided PowerShell script:
# Input bindings are passed in via param block.
param($Timer)# Add all your Azure Subscription Ids below
$subscriptionids = @”
[
“xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”
]
“@ | ConvertFrom-Json# Get GMT Standard Time zone
$date = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId([DateTime]::Now,”GMT Standard Time”)
$now = $dateforeach ($subscriptionid in $subscriptionids) {
# Selecting Azure Sub
Set-AzContext -SubscriptionId $SubscriptionID | Out-Null$CurrentSub = (Get-AzContext).Subscription.Id
If ($CurrentSub -ne $SubscriptionID) {
Throw “Could not switch to SubscriptionID: $SubscriptionID”
}$vms = Get-AzVM -Status | Where-Object {($_.Tags.RestartTime -ne $null)}
$now = $dateforeach ($vm in $vms) {
if (($vm.PowerState -eq ‘VM running’) -and ($now -gt $(get-date $($vm.tags.RestartTime))) ) {
Restart-AzVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -NoWait
Write-Warning “Restarting VM – $($vm.Name)”
}
}
}
Continue reading “Automating AVD Restarts with Azure Functions”