Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ForEach loop not finishing list

So I have an array of hostnames and I want run the command "Shutdown-VMGuest" on 45 host. I would like to turn off 20 at a time however when I get 40 done but it misses the last 5. This is the code below, does anyone have an idea what I am doing wrong?

    [System.Collections.ArrayList]$currentStartList = @()

    $i=0
    foreach ($vmHost in $PowerOffList){
        $i++
        [void]$currentstartList.Add($vmHost)
        if ($i -gt "19"){
            $vmToPowerOff = Get-VM -Name $currentstartList
            $Confirmation= Read-Host "`n Do you want to hard powerdown the following VMs (y/n)? $currentstartList"
            if ($Confirmation -eq 'y'){
                Write-Output "`n Trying to power down VMs safely: $vmToPowerOff"
                try {
                    Shutdown-VMGuest $vmToPowerOff
                }
                catch {
                    Write-Output "`n $vmToPowerOff has failed to power off safely"
                    $FailedVMs.Add($vmToPowerOff)
                }

                #clear lists
                [System.Collections.ArrayList]$currentstartList = @()
                $i=0
                sleep 5
            }
        }
    } 
like image 450
NW_92 Avatar asked Mar 02 '23 16:03

NW_92


1 Answers

For this kind of thing I'd suggest using a for loop instead:

for($i = 0; $i -lt $PowerOffList.Count; $i += 20){
    # grab the next 20 (or fewer) hosts
    $currentStartList = $PowerOffList[$i..($i + 19)]

    # prompt user to start the hosts here
}

When you pass an array of index values to the [] index accessor in PowerShell, it simply ignores indices that don't exist, so the 3rd time the loop executes, $PowerOffList[$i..($i + 19)] will simply result in the last 5 items

like image 171
Mathias R. Jessen Avatar answered Mar 05 '23 15:03

Mathias R. Jessen