Automation

 View Only
  • 1.  Foreach loop problem

    Posted Dec 22, 2021 08:58 PM

    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


  • 2.  RE: Foreach loop problem

    Posted Dec 22, 2021 09:01 PM

    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



  • 3.  RE: Foreach loop problem

    Posted Dec 22, 2021 09:07 PM

    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.

     



  • 4.  RE: Foreach loop problem

    Posted Dec 22, 2021 09:11 PM

    You are great. That was the issue!

    Thank you!