20211222
I am working on the following script, but having problems with the foreach loop.
# authenticate to the vSphere server
Connect-VIServer -Server MyVsphere.local -Credential (Get-Credential)
# change the name of MyClusterName to appropriate value before running
$cluster = "MyClusterName"
# This line will gather a list of VMs on this cluster sorted by vMemGB
$VMS = Get-VM -Location $cluster | select-object -Property $_.Name | Where-object {$_.PowerState -eq "PoweredOn"} | sort-object -Descending MemoryGB | Format-table -AutoSize
# Now since we have a list of the VMs of interest,
# we need to check if VMware tools is running.
# If VMware tools is running, we want to initiate graceful Guest OS shutdown
# If VMware tools are NOT running we will have to initiate a VM poweroff
$VMS | ForEach-Object {
if ($_.Guest.State -eq "Running") {
write-host "Shutting down $_.Name"
#for safety right now, I require confirmation to prevent unintended shutdown
#when this is used in emergency mode change $true to $false below
Shutdown-VMGuest -Confirm:$true
}
else {
write-host "Shutting down $_.Name"
#for safety right now, I require confirmation to prevent unintended shutdown
#when this is used in emergency mode change $true to $false below
Stop-VM -VM $_.Name -Confirm:$true
}
#Sleep 5 seconds
start-sleep -s 5
}
any assistance or advice would be appreciated.
I am trying to use Powershell 7.2.1 with VMware PowerCLI 12.4