你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用命令启动和停止开发测试实验室 VM

本文介绍如何使用 PowerShell 或 Azure CLI 命令为 Azure 开发测试实验室 VM 编写脚本或自动启动或停止。 例如,可以使用启动或停止命令来:

  • 测试三层应用程序,其中层需要按顺序启动。
  • 关闭 VM,以便在 VM 满足自定义条件时节省成本。
  • 在持续集成和持续交付(CI/CD)工作流开始和完成时启动和停止 VM。

注释

还可以使用 Azure 门户启动、停止或 重启 开发测试实验室 VM。 实验室管理员可以使用门户为实验室 VM 配置 自动启动自动关闭 计划和策略。

先决条件

启动或停止 VM

以下 PowerShell 脚本使用 Invoke-AzResourceAction PowerShell cmdlet 在实验室中启动或停止 VM。 ResourceId 参数是要启动或停止的实验室 VM 的完全限定的 ID。 Action 参数确定是启动还是停止 VM,具体取决于你所需要的操作。

  1. 如果使用 Cloud Shell,请确保已选择 PowerShell 环境。

  2. 使用 PowerShell Connect-AzAccount cmdlet 登录到 Azure 帐户。 如果有多个 Azure 订阅,则取消评论 Set-AzContext,并提供要使用的 <SubscriptionId>

    $sub = Get-AzSubscription -ErrorAction SilentlyContinue
    if(-not($sub))
    {
        Connect-AzAccount
    }
    
    # Set-AzContext -SubscriptionId "<Subscription ID>"
    
  3. 通过提供自己的 <lab name><VM name> 值来设置变量,并决定是 Start 还是 Stop VM。

    $devTestLabName = "<lab name>"
    $vMToStart = "<VM name>"
    $vmAction = "<Start or Stop>"
    
  4. 根据传递给 $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"
    }