VMware Cloud Community
UHViTeam
Contributor
Contributor

Foreach loop problem

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
Reply
0 Kudos
3 Replies
LucD
Leadership
Leadership

What are those problems?

Update: the Format-Table at the end of the pipeline where you populate the $VMS variable is wrong.
Remove that.
With that you will not have VirtualMachine objects in $VMS, but console formatted output


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

Reply
0 Kudos
UHViTeam
Contributor
Contributor

Shutting down Microsoft.PowerShell.Commands.Internal.Format.FormatStartData.Name
Stop-VM:
Line |
12 | Stop-VM -VM $_.Name -Confirm:$true
| ~~~~~~~
| Cannot validate argument on parameter 'VM'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

 

Reply
0 Kudos
UHViTeam
Contributor
Contributor

You are great. That was the issue!

Thank you!

Reply
0 Kudos