Use commands to start and stop DevTest Labs VMs

This article shows how you can use PowerShell or Azure CLI commands to script or automate start or stop for Azure DevTest Labs VMs. For example, you can use start or stop commands to:

  • Test a three-tier application where the tiers need to start in a sequence.
  • Turn off your VMs to save costs when they meet custom criteria.
  • Start and stop a VM when a continuous integration and continuous delivery (CI/CD) workflow begins and finishes. For an example of this workflow, see Run an image factory from Azure DevOps.

Note

You can also start, stop, or restart DevTest Labs VMs by using the Azure portal. Lab admins can use the portal to configure automatic startup and automatic shutdown schedules and policies for lab VMs.

Prerequisites

Start or stop a VM

The following PowerShell script starts or stops a VM in a lab by using the Invoke-AzResourceAction PowerShell cmdlet. The ResourceId parameter is the fully qualified ID for the lab VM you want to start or stop. The Action parameter determines whether to start or stop the VM, depending on which action you need.

  1. If you use Cloud Shell, make sure the PowerShell environment is selected.

  2. Use the PowerShell Connect-AzAccount cmdlet to sign in to your Azure account. If you have multiple Azure subscriptions, uncomment Set-AzContext and provide the <SubscriptionId> you want to use.

    $sub = Get-AzSubscription -ErrorAction SilentlyContinue
    if(-not($sub))
    {
        Connect-AzAccount
    }
    
    # Set-AzContext -SubscriptionId "<Subscription ID>"
    
  3. Set variables by providing your own values for <lab name>, <VM name>, and whether to Start or Stop the VM.

    $devTestLabName = "<lab name>"
    $vMToStart = "<VM name>"
    $vmAction = "<Start or Stop>"
    
  4. Start or stop the VM, based on the value you passed to $vmAction.

    # Get the lab information
    $devTestLab = Get-AzResource -ResourceType 'Microsoft.DevTestLab/labs' -ResourceName $devTestLabName
    
    # Start or stop the VM and return a succeeded or failed status
    $returnStatus = Invoke-AzResourceAction `
                        -ResourceId "$($devTestLab.ResourceId)/virtualmachines/$vMToStart" `
                        -Action $vmAction `
                        -Force
    
    if ($returnStatus.Status -eq 'Succeeded') {
        Write-Output "##[section] Successfully updated DTL machine: $vMToStart, Action: $vmAction"
    }
    else {
        Write-Error "##[error] Failed to update DTL machine: $vMToStart, Action: $vmAction"
    }