Skip to content

Instantly share code, notes, and snippets.

@blakedrumm
Last active April 17, 2024 03:27
Show Gist options
  • Save blakedrumm/23163b76af766e38bcc507743472c603 to your computer and use it in GitHub Desktop.
Save blakedrumm/23163b76af766e38bcc507743472c603 to your computer and use it in GitHub Desktop.
This script will toggle the Powerstate for VM's inside of Subscription(s) with specific tags.
param
(
[Parameter(Mandatory = $true)]
[String[]]$SubscriptionIds,
[Parameter(Mandatory = $true)]
[String]$TagName,
[Parameter(Mandatory = $true)]
[String]$TagValue,
[Parameter(Mandatory = $true)]
[Boolean]$PowerState, # true for start, false for stop
[Boolean]$WhatIf # test how the script will work, without making any changes to your environment
)
# Script to toggle Azure VM power states based on tags
# Requires PowerShell 7.2 or higher
# Author: Blake Drumm (blakedrumm@microsoft.com)
# Website: https://blakedrumm.com/
# Date created: March 31st, 2024
# Date modified: April 16th, 2024
# Ensures you do not inherit an AzContext in your runbook
$disableAzContextAutosave = Disable-AzContextAutosave -Scope Process
# Connect using a Managed Service Identity
try
{
# Connect to Azure
$AzConnection = Connect-AzAccount -Identity -AccountId cb02e61e-d392-48d7-936a-9b44bbf5f312 -ErrorAction Stop
Write-Output "$((Get-Date).ToLocalTime()) - Connected to Azure (Account Id: $($AzConnection.Context.Account.Id))"
}
catch
{
# Log the error and exit
Write-Output "$((Get-Date).ToLocalTime()) - Connection failed: $_"
exit 1
}
$SubscriptionIds | ForEach-Object {
# Initialize variables
$PS = $PowerState
$SubId = $_
try
{
# Set the subscription context
Write-Output "$((Get-Date).ToLocalTime()) - Subscription Id: $SubId"
$setAzContext = Set-AzContext -SubscriptionId $SubId -ErrorAction Stop
}
catch
{
# Log the error and exit
Write-Output "$((Get-Date).ToLocalTime()) - Encountered error: $_"
exit 1
}
# Fetch VMs with the specified tag
$vms = Get-AzResource -ResourceType Microsoft.Compute/virtualMachines -TagName $TagName -TagValue $TagValue
# Start or stop the VMs based on the desired state
$vms | ForEach-Object -Parallel {
$vm = $_
$WhatIf = $using:WhatIf
$Power = $using:PS
# Fetch VM status
$x = 0
do
{
$x++
try
{
$vmStatus = Get-AzVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Status -ErrorAction Stop
# This will only be set to 2 if the command above is able to successfully fetch the VM status
$x = 2
}
catch
{
Write-Output "$((Get-Date).ToLocalTime()) - Encountered error: (VM Name: $($vm.Name)) $_"
}
}
until ($x -eq 2)
# Extract the power state of the VM
$vmPowerState = $vmStatus.Statuses | Where-Object { $_.Code -like 'PowerState/*' } | Select-Object -ExpandProperty Code
# Start or stop VM based on the desired state
if (($Power -eq $true) -and ($vmPowerState -ne 'PowerState/running'))
{
if ($WhatIf)
{
Write-Output "$((Get-Date).ToLocalTime()) - What if: Starting $($vm.Name)"
}
else
{
# Start the VM
Start-AzVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Verbose
Write-Output "$((Get-Date).ToLocalTime()) - Starting $($vm.Name)"
}
}
elseif ($Power -eq $false -and $vmPowerState -notmatch 'PowerState/(deallocated|stopped)')
{
if ($WhatIf)
{
Write-Output "$((Get-Date).ToLocalTime()) - What if: Stopping $($vm.Name)"
}
else
{
# Stop the VM
Stop-AzVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force -Verbose
Write-Output "$((Get-Date).ToLocalTime()) - Stopping $($vm.Name)"
}
}
else
{
# Log the VM is already in the desired state
Write-Output "$((Get-Date).ToLocalTime()) - VM $($vm.Name) is already in the desired state (PowerState: $Power). (Current VM PowerState: $vmPowerState)"
}
} -ThrottleLimit 4 # Example throttle limit
}
Write-Output "$((Get-Date).ToLocalTime()) - Script completed!"
<#
Copyright (c) Microsoft Corporation. MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment