I'm automating an Azure Virtual Machine using powershell, just starting and stopping one machine on a schedule. I've done this before, but I came across this code snippet which has an extra step, and I want to make sure I'm not missing something important:

# 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                 
    }     
}  

So I would have just called Stop-AzureVM... What does the check to InstanceStatus do? Does it, say, prevent the VM from shutting down if it's in the middle of installing updates? I'm thinking no, and that this is a check that's more important for other commands. But now I want to know.

I tried searching around and found it used in several unrelated code samples, but I've been unable to find an explanation.

有帮助吗?

解决方案

ReadyRole is the steady state for an Azure VM. It essentially means it's not starting, stopping, provisioning, transitioning, stopped etc.

To me, I think the line $vm.InstanceStatus -eq 'ReadyRole' is just a basic check on the machine status. If you try to shutdown, or run any other command on the VM whilst it is busy doing something, your command will fail with an error anyway.

I just ran a test trying to stop a VM after I'd started it from the web management console and this is what I received:

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

In this case it's because the status was most likely starting

However, once the VM is stopped, issuing another stop command (whilst daft) works without any apparent problem.

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

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

So, in conclusion, I'd say it's a tidy bit of scripting diligence to avoid pointless / impossible operations during the script execution.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top