VMware Cloud Community
winterwy
Contributor
Contributor

I use powercli to shutdown one vm, but actually all VMs in cluster are down

Hi,

I wanted to use below script to shutdown one VM.

but all VMs in cluster are off.

I use wildcard * because some VM name is fully qualified name and same are short name.

when I manually run get-vm servername*, I only get one result.

how can it happen?

            $servername = $server+"*"

            $tempvm = get-vm ($servername) -ErrorAction SilentlyContinue

            if ($tempvm) {

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

                   Stop-VM -VM $tempvm -Confirm:$false

                }

                $shutdown_vmlist += $server

            }

0 Kudos
3 Replies
NathanosBlightc
Commander
Commander

First, use "Shutdown-vmguest" instead of stop-vm to shut it down, not power-off!

Then you didn't specify a metric for filtering specific VMs. You just mentioned for each host if there is a power-on VM, force it to power-off.

Please mark my comment as the Correct Answer if this solution resolved your problem
0 Kudos
scott28tt
VMware Employee
VMware Employee

Moderator: Thread moved to the PowerCLI area.


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

Although I am a VMware employee I contribute to VMware Communities voluntarily (ie. not in any official capacity)
VMware Training & Certification blog
0 Kudos
LucD
Leadership
Leadership

You can use the wildcard, but you have to remember that variable substitution happens in a string.

Instead of using an If-construct, you can use Where-Object, the pipeline and a foreach loop.

Also, if you want to add results to an array, you will have to declare the array.

This will stop all VMs whose Displayname starts with 'VMxyz'

$server = 'VMxyz'


$shutdown_vmlist = @()


Get-VM -Name "$server*" |

where{$_.PowerState -eq 'PoweredOn'} |

ForEach-Object -Process {

    Stop-VM -VM $_ -Confirm:$false

    $shutdown_vmlist += $server

}

$shutdown_vmlist


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

0 Kudos