Hi Akhila Anne
Welcome to Microsoft Q&A Forum, thank you for posting your query here!
Please follow the below steps:
1)Create an Automation Account and ensure that your automation account has the required permissions
2)Create two runbooks: one for stopping VMs and another for starting VMs.
Runbook 1:
Use the following PowerShell script to stop VMs based on specified tags.
# Connect to Azure with system-assigned managed identity
$AzureContext = (Connect-AzAccount -Identity).context
# set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
# Connect to Azure (if not already connected)
#Connect-AzAccount
Select-AzSubscription -Subscription "SubscriptionName"
# Define the tag key and value
$TagKey = "Environment"
$TagValue = "dev-Autoshutdown"
# Get all VMs that have the specified tag value
$VMs = Get-AzVM | Where-Object { $_.Tags[$TagKey] -eq $TagValue }
# Stop the VMs
foreach ($VM in $VMs) {
Write-Host "Stopping VM: $($VM.Name) in Resource Group: $($VM.ResourceGroupName)"
#For Stop use the Below Command in the Stop Dev VMs Run book
Stop-AzVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName -Force
}
Write-Host "All dev-test tagged VMs have been powered off."
Runbook 2:
Use the following PowerShell script to start VMs based on specified tags.
# Connect to Azure with system-assigned managed identity
$AzureContext = (Connect-AzAccount -Identity).context
# set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
# Connect to Azure (if not already connected)
#Connect-AzAccount
Select-AzSubscription -Subscription "SubscriptionName"
# Define the tag key and value
$TagKey = "Environment"
$TagValue = "dev-Autostart"
# Get all VMs that have the specified tag value
$VMs = Get-AzVM | Where-Object { $_.Tags[$TagKey] -eq $TagValue }
# Start the VMs
foreach ($VM in $VMs) {
Write-Host "Starting VM: $($VM.Name) in Resource Group: $($VM.ResourceGroupName)"
#For start use the Below Command in the Start Dev VMs Run book
Start-AzVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName
}
Write-Host "All dev-test tagged VMs have been powered on."
Please do not forget to "Accept the answer” and “upvote it” wherever the information provided helps you, this can be beneficial to other community members.it would be greatly appreciated and helpful to others.