2017-05-03 55 views
1

以下是我正在嘗試執行的操作:我有一個具有多個集羣的vSphere設置,在這些集羣下有幾個主機。PowerCLI遍歷集羣和主機

我正在嘗試編寫一個腳本,它穿過集羣並在每個集羣內部,將主機置於維護模式,將其移動到集羣外部,啓動/停止VM,向其添加內存,然後將主機移回進入它被移出的羣集。

這是我到目前爲止。內部循環工作,但外部循環正在使所有內容都運行兩次,並在內部循環中添加集羣名稱$cluster

任何想法?我只想讓內部循環爲每個集羣中的所有主機運行。

我加了-WhatIf進行測試,可以忽略這些。

Connect-VIServer vcenter01 

$clusters = Get-Cluster 
$esxhosts = Get-Cluster $clusters | Get-VMHost 
$Datacenter = "Datacenter01" 
$sleep = 1 

& { 
    foreach ($cluster in $clusters) { 
     foreach ($esxhost in $esxhosts) { 
      Set-VMHost $esxhost -State Maintenance -WhatIf 
      Move-VMhost $esxhost -Destination $Datacenter -WhatIf 
      Set-VMHost $esxhost -State Connected -WhatIf 
      Sleep $sleep 
      Stop-VMGuest -Vm Z-VRA-$esxhost -Confirm:$false -WhatIf 
      Sleep $sleep 
      Set-VM -Vm Z-VRA-$esxhost -MemoryGB 6 -Confirm:$false -WhatIf 
      Start-VM -Vm Z-VRA-$esxhost -WhatIf 
      Sleep $sleep 
      Move-VMhost $esxhost -Destination $cluster -WhatIf 
     } 
    } 
} 

Disconnect-VIServer vcenter01 

這裏是一個工作副本看起來像(感謝@Ansgar Wiechers):

我在一些代碼添加到啓動/每個羣集上停止HA接入控制,因爲它的工作原理通過它。這樣可以避免虛擬機在維護模式下騰空的問題,如果您的資源不足。

Connect-VIServer vcenter01 

$Datacenter = "Datacenter01" 
$sleep = 1 

Get-Cluster | ForEach-Object { 
$cluster = $_ 
Set-Cluster -HAAdmissionControlEnabled $false -Cluster $cluster -Confirm:$false -Whatif 
$cluster | Get-VMHost | ForEach-Object { 
     Set-VMHost $_ -State Maintenance -WhatIf 
     Move-VMhost $_ -Destination $Datacenter -WhatIf 
     Set-VMHost $_ -State Connected -WhatIf 
     Sleep $sleep 
     Stop-VMGuest -Vm Z-VRA-$_ -Confirm:$false -WhatIf 
     Sleep $sleep 
     Set-VM -Vm Z-VRA-$_ -MemoryGB 6 -Confirm:$false -WhatIf 
     Start-VM -Vm Z-VRA-$_ -WhatIf 
     Sleep $sleep 
     Move-VMhost $_ -Destination $cluster -WhatIf 


    } 
    Set-Cluster -HAAdmissionControlEnabled $true -Cluster $cluster Confirm:$false -Whatif 
} 


Disconnect-VIServer vcenter01 

回答

1

本聲明爲您提供了所有集羣:

$clusters = Get-Cluster 

本聲明爲您提供了所有的虛擬機管理程序的所有集羣的

$esxhosts = Get-Cluster $clusters | Get-VMHost 

因爲你的內部循環已經結束的所有hypervisers迭代所有羣集,迭代外部循環中的羣集都會爲每個羣集重複該操作。對於兩個集羣,你得到的結果兩次,三個集羣你會得到結果的三倍,依此類推。

由於在內部循環的最後操作是不支持羣集無關,你的代碼實際上可能,如果你刪除的雞開關碰壞。您需要枚舉管理程序每個集羣。我沒有訪問到vSphere系統,但我想這樣的事情應該做你想要什麼:

Get-Cluster | ForEach-Object { 
    $cluster = $_ 
    $cluster | Get-VMHost | ForEach-Object { 
     Set-VMHost $_ -State Maintenance -WhatIf 
     ... 
     Move-VMhost $_ -Destination $cluster -WhatIf 
    } 
} 

附註:在你的循環中的& { ... }是沒有意義的。只要放下它。

+0

明白了,感謝您的幫助。我明白我做錯了什麼。我會測試你給我的東西。 – Nov2009