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
- Admin access to a lab VM in DevTest Labs.
- Access to Azure PowerShell. You can use the Azure Cloud Shell PowerShell environment, or install Azure PowerShell to use a physical or virtual machine. If necessary, run
Update-Module -Name Az
to update your installation.
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.
If you use Cloud Shell, make sure the PowerShell environment is selected.
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>"
Set variables by providing your own values for
<lab name>
,<VM name>
, and whether toStart
orStop
the VM.$devTestLabName = "<lab name>" $vMToStart = "<VM name>" $vmAction = "<Start or Stop>"
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" }