Getting Azure Automation runbooks to shut down your virtual machines (or turn them on) automatically is not new. There are a lot of scripts out there that could do it for you. You can also write one yourself. It's not that complicated. I did it J Just kidding…
There are a couple of ways my PowerShell scripts are different:
- First, the scripts that automatically start/stop Azure virtual machines take the weekend into account. Scripts will not turn your machines on or off on the weekends. After all, you probably do not want to automatically turn on your virtual machines in Azure early in the morning on the weekend, just so that you can turn them off at the end of the day on the weekend. Seems like a waste, right? Anyways, this small change should save you a few bucks.
- Second, the scripts adjust the schedule from UTC to the time zone you need. It looks like when the scripts that are part of Azure Automation runbooks run, they use UTC time. So, if you're in Toronto, script will think that the weekend starts 5 hours earlier. It's not bad, I guess. But, it also means that the weekend will end 5 hours earlier, and that just not right and need to be fixed.
Below is a code snippet that makes the above mentioned happen:
$UTCTime = (Get-Date).ToUniversalTime()
$TZ = [System.TimeZoneInfo]::FindSystemTimeZoneById("Eastern Standard Time")
$LocalTime = [System.TimeZoneInfo]::ConvertTimeFromUtc($UTCTime, $TZ)
$day = $LocalTime.DayOfWeek
if ($day -eq 'Saturday' -or $day -eq 'Sunday')
Write-Output ("It is " + $day + ". Cannot use a runbook to start VMs on a weekend.")
The complete scripts that start or stop Azure virtual machines can be downloaded from OneDrive. Enjoy.