你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
本文介绍如何使用 PowerShell 或 Azure CLI 命令为 Azure 开发测试实验室 VM 编写脚本或自动启动或停止。 例如,可以使用启动或停止命令来:
- 测试三层应用程序,其中层需要按顺序启动。
- 关闭 VM,以便在 VM 满足自定义条件时节省成本。
- 在持续集成和持续交付(CI/CD)工作流开始和完成时启动和停止 VM。
先决条件
- 对 DevTest Labs 中的 实验室 VM 进行管理员访问。
- 访问 Azure PowerShell。 可以使用 Azure Cloud Shell PowerShell 环境,或 安装 Azure PowerShell 以使用物理或虚拟机。 如有必要,请运行 Update-Module -Name Az以更新安装。
启动或停止 VM
以下 PowerShell 脚本使用 Invoke-AzResourceAction PowerShell cmdlet 在实验室中启动或停止 VM。 
              ResourceId 参数是要启动或停止的实验室 VM 的完全限定的 ID。 
              Action 参数确定是启动还是停止 VM,具体取决于你所需要的操作。
- 如果使用 Cloud Shell,请确保已选择 PowerShell 环境。 
- 使用 PowerShell Connect-AzAccount cmdlet 登录到 Azure 帐户。 如果有多个 Azure 订阅,则取消评论 - Set-AzContext,并提供要使用的- <SubscriptionId>。- $sub = Get-AzSubscription -ErrorAction SilentlyContinue if(-not($sub)) { Connect-AzAccount } # Set-AzContext -SubscriptionId "<Subscription ID>"
- 通过提供自己的 - <lab name>和- <VM name>值来设置变量,并决定是- Start还是- StopVM。- $devTestLabName = "<lab name>" $vMToStart = "<VM name>" $vmAction = "<Start or Stop>"
- 根据传递给 - $vmAction的值启动或停止 VM。- # 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" }