Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Azure by (13.1k points)
I have a multiple Virtual Machines that are present in different resource groups and I want to start or shut down them as per requirement. Can anyone help me how I can able to achieve this using Azure runbook?

1 Answer

0 votes
by (26.7k points)

You can use PowerShell workflow which will help you for scheduled jobs. Given below is the script, you can change the credentials as per your requirement:

workflow Stop-VM

{

    $myCred = Get-AutomationPSCredential -Name "yourVmUser"

    $userName = $myCred.UserName

    $securePassword = $myCred.Password

    $myPsCred = New-Object System.Management.Automation.PSCredential ($userName,$securePassword)

    Connect-AzAccount -Credential $myPsCred

    $vms = Get-AzVM | Where-Object {$_.Tags.Keys -eq "yourTagName" -or $_.Tags.Keys -eq "yourTagValue"} | Select-Object Name, ResourceGroupName, Tags

    foreach -parallel ($vm in $vms)

    { 

        $status = (Get-AzVm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Status).Statuses[1].DisplayStatus

        if ($status -ne "VM deallocated")

        {

            Write-Output "Stopping $($vm.Name)";         

            Stop-AzVm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force;

        } 

    } 

}

I hope this will help.

Want to become an Azure expert? join Azure Developer Certification now!!

Browse Categories

...