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
}
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With