NW_*_*_92 4 powershell foreach
所以我有一个主机名数组,我想在 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
对于这种事情,我建议改用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
}
Run Code Online (Sandbox Code Playgroud)
当您将索引值数组传递给[]PowerShell 中的索引访问器时,它只会忽略不存在的索引,因此第三次循环执行时,$PowerOffList[$i..($i + 19)]只会产生最后 5 个项目
| 归档时间: |
|
| 查看次数: |
45 次 |
| 最近记录: |