1
votes

I have a Powershell script that checks on a set of VM status before starting them. If the VM'S are in deallocating mode there should be a sleep and retry on 30 seconds. The code does not do a a retry. The code does a vm start in batches on 2 for vm's with wilcards as mentioned below in an order.

Need help if possible

$ResName= "resvmtest"
$action="start"
if($action -eq "start"){
    $vnames=@('*dom*','*DBs*','*')
    foreach($vname in $vnames) {
        Write-Host "Starting VM with "$vname
        $vmList = Get-AzVM -ResourceGroupName $ResName -Name $vname -Status | Select-Object Name, PowerState, ResourceGroupName

        do{
            $batch = @{
                Skip  = 0
                First = 2
            }

            do{

                foreach($vm in ($vmList | Select-Object @batch)){
                    $Stoploop = $false
                    [int]$Retrycount = "0"

                    do {
                        try {
                            if($vm.PowerState -eq "VM Deallocated"){
                                Write-Host "Job completed"
                                $Stoploop = $true
                            }
                        }
                        catch {

                            if ($vm.PowerState -eq "VM Deallocatting") {
                                Write-Host "VM Still not Deallocated"
                                Start-Sleep -Seconds 10
                                $Retrycount = $Retrycount + 1
                            }
                        }
                    }
                    While ($Stoploop -eq $false)
                    $params = @($vm.Name, $vm.ResourceGroupName,$vm.PowerState)
                    $job = Start-Job -ScriptBlock {
                        param($ComputerName,$serviceName,$statuses)

                        Start-AzVM -Name $ComputerName -ResourceGroupName $serviceName

                    } -ArgumentList $params

                }
                Wait-Job -Job $job
                Get-Job | Receive-Job
                $batch.Skip += 2
            }
            until($batch.skip -ge $vmList.count)

        }
        while($job.state -ne "Completed")
    }
}
1
How's going? Has your issue got solved ?Stanley Gong

1 Answers

0
votes

If you just want to wait for a VM's PowerState turns to VM Deallocated from VM Deallocatting, try the code below:

$vms = Get-AzVm  -Status| Select-Object Name, PowerState,ResourceGroupName

#pick certain vm for demo here.
$vm = $vms[1]

$retryCount = 0
while($vm.PowerState -eq 'VM deallocating'){
    Write-Host "waiting for VM deallocated..."
    Start-Sleep -Seconds 5
    $retryCount +=1
    Write-Host "check count:$retryCount"
    #get latest vm status
    $vm.PowerState = (Get-AzVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Status).Statuses[1].DisplayStatus
    Write-Host "vm current state:"$vm.PowerState
}

Write-Host "vm new state:" + $vm.PowerState

Result:

enter image description here