VMware Cloud Community
bliebowitz
Contributor
Contributor
Jump to solution

Foreach loop help excluding a VM

I need to shutdown all the VMs in a particular vCenter due to work being done on the underlying storage.  I have a script that would normally do this, but in this case, the vCenter is virtual.  I need the foreach loop to skip it. 

I thought I could do a nested loop but my tests aren't working...  Any pointers or suggestions? 

Thanks in advance!

----------------------------------------

Connect-VIServer $server

# Gets the list of all VMs in a specific folder

$vms = Get-datacenter -Name "DATACENTER" | Get-VM

# Shuts down the VMs in the datacenter that are in a powered on state.

Foreach ($vm in $vms){

if ($vm.PowerState -eq "PoweredOn"){

  if ($vm.name -ne "vcenter01") {

  $vmMOR = $vm|Get-View

  if($vmMOR.Config.Tools.ToolsVersion -ne "0"){ 

  #gracefully shutdown

  Shutdown-VMGuest -VM $vm -Confirm:$false

  sleep -Seconds 60

  }

  #forcefully stopping VM

  Stop-VM -VM $vm -Confirm:$false

  }

  }

}

sleep -seconds 60

Shutdown-VMGuest -VM vcenter01 -Confirm:$false

- Ben Liebowitz, VCP
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

Try like this

Connect-VIServer $server

# Gets the list of all VMs in a specific folder

$vms = Get-datacenter -Name "DATACENTER" | Get-VM |

    where {$_.Name -ne "vcenter01" -and $_.PowerState -eq "PoweredOn"}

# Shuts down the VMs in the datacenter that are in a powered on state.

Foreach ($vm in $vms){

  if($vm.ExtensionData.Config.Tools.ToolsVersion -ne "0"){

  #gracefully shutdown

    Shutdown-VMGuest -VM $vm -Confirm:$false

    sleep -Seconds 60

  }

  else{

  #forcefully stopping VM

      Stop-VM -VM $vm -Confirm:$false

  }

}

sleep -seconds 60

Shutdown-VMGuest -VM vcenter01 -Confirm:$false


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

2 Replies
LucD
Leadership
Leadership
Jump to solution

Try like this

Connect-VIServer $server

# Gets the list of all VMs in a specific folder

$vms = Get-datacenter -Name "DATACENTER" | Get-VM |

    where {$_.Name -ne "vcenter01" -and $_.PowerState -eq "PoweredOn"}

# Shuts down the VMs in the datacenter that are in a powered on state.

Foreach ($vm in $vms){

  if($vm.ExtensionData.Config.Tools.ToolsVersion -ne "0"){

  #gracefully shutdown

    Shutdown-VMGuest -VM $vm -Confirm:$false

    sleep -Seconds 60

  }

  else{

  #forcefully stopping VM

      Stop-VM -VM $vm -Confirm:$false

  }

}

sleep -seconds 60

Shutdown-VMGuest -VM vcenter01 -Confirm:$false


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

bliebowitz
Contributor
Contributor
Jump to solution

Thank you, sir! 

That worked!

- Ben Liebowitz, VCP
0 Kudos