所以我有一个主机名数组,我想在 45 主机上运行命令“Shutdown-VMGuest”。我想一次关闭 20 次,但是当我完成 40 次时却错过了最后 5 次。这是下面的代码,有人知道我做错了什么吗?
[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
改为循环:
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
}
当您将索引值数组传递给
[]
时PowerShell 中的索引访问器,它只是忽略不存在的索引,因此循环执行第 3 次,$PowerOffList[$i..($i + 19)]
只会导致最后 5 个项目
关于powershell - ForEach 循环未完成列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60743068/