Nested Foreach in PowerShell

Hi All,


I am training my power shell skiils and challenging my abilities, i need you assist with the following easy task.


I want to get any VM and his own cluster on PowerCLI.


I know that i can get this details using HOST.PARENT but i insist to get this details via “Cluster” in order to learn work with two for each, for some reason it doesn’t work for me, can you assist?


$Result =@(

$VMList = (Get-VM).Name 
$Clusters = (get-cluster).Name
Foreach ($Cluster in $Clusters){
Foreach ($vm in $VMList){ 
"VM Name" = $vm 
"Cluster Name"= $Cluster


I’m not sure your code is doing anything other than combining all VMs with all clusters. Maybe this is what you’re looking for?

foreach($vm in (get-vm))
    get-vmhost -vm $vm | foreach{
            VM      = $
            Host    = $
            Cluster = $_.parent

If you want to find the VMs within each cluster, you can the following with calculated properties:

# Get all clusters
$clusters = Get-Cluster
# Loop through each cluster
$result = foreach ($cluster in $clusters) {
     # Use calculated properties to create custom object
     Get-VM -Location $cluster | Select @{n='Cluster';e={$cluster.Name}},@{n='VM Name';e={$_.Name}}