Azure Automation Start/Stop VMs PowerShell

If you have a number of Virtual Machines and want to automate the start and stop process of the Azure Virtual Machines, the better idea here is to use your own PowerShell script using the PowerShell Workflow.

Make sure to set the credentials in the Automation account with the needed permission for the user.

The PowerShell script is as below

Note: The below script is to stop the virtual machines from starting the VMs. You need to make a slight change to the script below, like instead of Stop-AzVm, use Start-AzVm, and then you will have to change the condition $status.

workflow Stop-VM
{
    $Cred = Get-AutomationPSCredential -Name "VMUserName"
    $uName = $Cred.UserName
    $pswd = $Cred.Password
    $PsCred = New-Object System.Management.Automation.PSCredential ($uName,$pswd)

    Connect-AzAccount -Credential $PsCred
        
    $myvms = Get-AzVM | Where-Object {$_.Tags.Keys -eq "NameofyourTag" -or $_.Tags.Keys -eq "Valueofyourtag"} | Select-Object Name, ResourceGroupName, Tags
        
    foreach -parallel ($vm in $myvms)
    { 
        $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;
        } 
    } 
}