powershell - 在启动或停止 Azure VM 之前是否需要检查实例状态?

标签 powershell azure automation virtual-machine azure-powershell

我正在使用 powershell 自动化 Azure 虚拟机,只需按计划启动和停止一台计算机。我以前已经这样做过,但我遇到了这个代码片段,其中有一个额外的步骤,我想确保我没有遗漏一些重要的东西:

# Shutdown VM(s)
$vmList = ('VM1', 'VM2', 'VM3')
$svcName = 'servicename'

For ( $vmCount = 0; $vmCount -lt $vmList.Count; $vmCount++) {

    $vm = Get-AzureVM `
        -ServiceName $svcName `
        -Name $vmList[$vmCount]

    if ( $vm.InstanceStatus -eq 'ReadyRole' ) {

        Stop-AzureVM `
            -ServiceName $vm.ServiceName `
            -Name $vm.Name `
            -Force                 
    }     
}  

所以我会直接调用 Stop-AzureVM...检查 InstanceStatus 的作用是什么?例如,如果虚拟机正在安装更新,它是否会阻止虚拟机关闭?我认为不,这是一个对其他命令更重要的检查。但现在我想知道。

我尝试四处搜索,发现它在几个不相关的代码示例中使用,但我一直找不到解释。

最佳答案

ReadyRole 是 Azure VM 的稳定状态。它本质上意味着它没有启动、停止、配置、转换、停止等。

对我来说,我认为 $vm.InstanceStatus -eq 'ReadyRole' 这行只是对机器状态的基本检查。如果您在虚拟机正忙于执行某些操作时尝试关闭虚拟机或在虚拟机上运行任何其他命令,则您的命令无论如何都会失败并出现错误。

我刚刚运行了一个测试,试图在从 Web 管理控制台启动虚拟机后停止该虚拟机,这就是我收到的结果:

stop-azurevm : ConflictError: Windows Azure is currently performing an operation with x-ms-requestid
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx on this deployment that requires exclusive access.
At line:1 char:1

在本例中,这是因为状态很可能是开始

但是,一旦虚拟机停止,发出另一个停止命令(虽然愚蠢)就不会出现任何明显的问题。

PS > get-azurevm
ServiceName                             Name                                    Status
-----------                             ----                                    ------
vm                              cloudservice                           StoppedDeallocated

PS > stop-azurevm -servicename cloudservice -name vm
OperationDescription                    OperationId                             OperationStatus
--------------------                    -----------                             ---------------
Stop-AzureVM                            xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx    Succeeded

因此,总而言之,我想说这是一种整洁的脚本编写工作,可以避免在脚本执行期间出现无意义/不可能的操作。

关于powershell - 在启动或停止 Azure VM 之前是否需要检查实例状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23565984/

相关文章:

c# - 如何使用 C# 从 Azure 删除 blob 不可变文件

c# - 从 C# 调用带参数的 PowerShell 脚本

powershell - 如何使用 Windows Powershell 提取嵌套文件夹中的所有 zip 文件

reactjs - 如何使 'forgot password' 在带有 Azure AD B2C 的 React-aad-msal 中工作?

azure - Azure 上的 StackExchange.Redis 抛出执行获取超时且无连接可用异常

c# - 使用任务计划程序并且用户已注销时如何找到 AutomationElement?

networking - 调用 tcp : lookup xxx. xxx.xxx.xxx: 没有这样的主机

python - 使用 python/COM 的 Windows 应用程序自动化

regex - Powershell特定字符与功能不匹配

.net - Powershell 中的 AppDomain.DoCallBack