Azure

Azure Virtual machine Start and Stop power shell script

Azure virtual machine costing applied based on server is on and this server should not on all the time hence we have created power shell scripts which help to reduce the cost .

param(
    [Parameter(Mandatory=$True)]
    [string]$VMAction,
     
    [Parameter(Mandatory=$True)]
    [string]$ResourceGroupName,
 
    [Parameter(Mandatory=$True)]
    [string[]]$VirtualMachines
)



foreach ($VirtualMachine in $VirtualMachines)  
{
    Write-Output "Loop Running for Running for $($VirtualMachine)"

    #$myVirtualMachine = Get-AzAnalysisServicesServer -ResourceGroupName $ResourceGroupName -Name $VirtualMachine
	$VMDetail = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VirtualMachine  -Status
       
	foreach ($VMStatus in $VMDetail.Statuses)
	{ 
		  if ($VMStatus.Code -match "PowerState/")
		  {
			$VMStatusDetail = $VMStatus.DisplayStatus
		  }
		  else
		  {
			$VMStatusDetail = "Not Found"
		  }
	}
	
	
    if (!$VMDetail)
    {
        Write-Error "$($VirtualMachine) not found in $($ResourceGroupName)"
        return
    }
    else
    {
        Write-Output "Current status of $($VirtualMachine): $($VMStatusDetail)"
    }

	#Start Azure VM
    if (($VMAction -eq "Start" -And $VMStatusDetail -eq "VM deallocated"))
    {
        Write-Output "Now starting $($VirtualMachine)"
        $null = Start-AzVM -ResourceGroupName $ResourceGroupName -Name $VirtualMachine
    }
    # Stop Azure VM
    elseif(($VMAction -eq "Stop" -And $VMStatusDetail -eq "VM running"))
    {
		Write-Output "Now stopping $($VirtualMachine)"
		$null = Stop-AzVM -ResourceGroupName $ResourceGroupName -Name $VirtualMachine -Force		
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top