Start/Stop multiple Azure VM


There are situations where we need to start and stop the multiple AzureVM together hence the below script to cater the need. Well you can use AzureRM PS module and AZ module as well & cmdlet would change as per the module installed on your system.

Second thing to note is the that there are two ways to get the Azure VM it could belong to the same Resource group or different hence we can have below script written down in two ways. Motive here is getting the AzureVM name in the for-each loop and running the stop or start command on each VM coming out of the "if" construct.

So you need to login to Azure account first and do the necessary change as per requirement. 

Login-AzureRmAccount  # login to Azure account

$vms = gc -Path C:\computer.txt  #put name of azure vm in the text file

#$vms = (get-azurermvm -resourcegroup "rgname").name (remove #if need to pick VM from RG)

 foreach ($vm in $vms)
{
    $resource = Find-AzurermResource -ResourceNameEquals $vm -ResourceType "Microsoft.Compute/virtualMachines"
    if($resource -ne $null)
    { 
        Write-Output "Stopping virtual machine..." + $vm
        Stop-AzurermVM -ResourceGroupName $resource.ResourceGroupName -Name $vm -Force
    } 
    else
    {
        Write-output "Virtual machine not found:" + $vm
    }
}


you can also download this code from github :

https://github.com/ps-world/Azure-VM/blob/master/startstopvm.ps1


No comments:

Post a Comment

Azure DevOps

Azure DevOps is a suite of development tools provided by Microsoft, designed to support the entire development lifecycle of a software proje...