Skip to content

PowerShell | VMware Powermanagement

A few PowerShell cmdlets to manage vm power state from Hosts defined in an array.

With this basic structure you can combine several conditions -> very useful if you are going to maintain your vSphere environment.

Connect vCenter

At first we need to establish a connection from our PowerShell console to the vCenter Server:

PowerShell
$vcntsrv = 'your vcenter server fqdn'
connect-viserver $vcntsrv

Fetch VMs

Get all VMs from Host machines, which are stored in an array. You separate each entry with a coma except for the last value:

PowerShell
$myhosts = @(
'host1.fqdn',
'host2.fqdn',
'etc.'
)

Loop

Now we are going to build a foreach loop, to receive all VMs on each Host with the defined properties as a table (Note! if you are going to add more pipes behind the properties, you have to remove ft):

PowerShell
foreach($eachhost in $myhosts){
   get-vmhost -name $eachhost | get-vm | select vmhost, name, numcpu, memorygp, folder | ft
}

Shutdown

Shutdown all VMs on the specified Hosts -> $myhosts -> this is the gracefully method, therefore VMWare-Tools have to be installed on the VM. Otherwise you can use the “hard” mode, replace ‘shutdown-vmguest’ with ‘stop-vm’:

PowerShell
foreach($eachhost in $myhosts){
   get-vmhost -name $eachhost | get-vm | Where-Object {$_.State -eq "Running"}  | shutdown-vmguest -confirm:$false 
}

Turn On

Same as #4 but instead of shutting the VMs down, we are going to turn them on:

PowerShell
foreach($eachhost in $myhosts){
   get-vmhost -name $eachhost | get-vm | Where-Object {$_.State -eq "Off"}  | start-vm -confirm:$false 
}

Maintenance Mode

Put all Host system into maintenance mode and shut down VMs:

PowerShell
foreach($eachhost in $myhosts){
   set-vmhost -vmhost $eachhost -state maintenance
   start-sleep -s 2 #wait 2 seconds, because sometimes the next cmd struggles otherweise
    get-vmhost -name $eachhost | get-vm | Where-Object {$_.State -eq "Running"}  | shutdown-vmguest -confirm:$false 
}

Disconnect vCenter

Of course, we don’t forget to disconnect from our vCenter Server/s:

PowerShell
disconnect-viserver -server *

Cheers!