Shutting down a Virtual Machine using PowerCLI

VMware PowerCLI allows us to shutdown a guest operating system on a Virtual machine (assuming VMTools are installed) but the command to do this- Shutdown-VMGuest -returns straight away. In a script we may wish to wait for the VM to power down before continuing, this can be done as follows.
The text myvirtualcenterserver and myvirtualmachinename in the script below should be replaced with the appropriate values.

#Load the VMWare PowerCLI command set
add-pssnapin VMWare.VimAutomation.Core
#Connect to the Virtual Center Server
Connect-VIServer -Server myvirtualcenterserver
#Get the VM
$MyVM = Get-VM -Name myvirtualmachinename
#Initiate Shutdown of the OS on the VM if it is on.
if ($MyVM.PowerState -eq "PoweredOn") {
   Write-Host "Shutting Down" $MyVM
   Shutdown-VMGuest -VM $MyVM
   #Wait for Shutdown to complete
   do {
      #Wait 5 seconds
      Start-Sleep -s 5
      #Check the power status
      $MyVM = Get-VM -Name myvirtualmachinename
      $status = $MyVM.PowerState
   }until($status -eq "PoweredOff")

5 thoughts on “Shutting down a Virtual Machine using PowerCLI

  1. Matty-uk

    When I try this it fails @ ‘-Name’ in the line of ‘$MyVM = Get-VM -Name $args[0]’.

    Get-VM : Cannot validate argument on parameter ‘Name’. The argument is null or
    empty. Supply an argument that is not null or empty and then try the command
    At line:1 char:23
    + $MyVM = Get-VM -Name $args[0]
    + ~~~~~~~~
    + CategoryInfo : InvalidData: (:) [Get-VM], ParameterBindingValid
    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutom

    Any ideas on how to fix this?

    1. chris Post author

      Matty-uk, good point. I’ve updated the script to fix this, the line should actually read

      $MyVM = Get-VM -Name myvirtualmachinename

      Again, myvirtualmachinename should be replaced with the VM name in question.

      The $args[0] entry was actually a leftover from my script (I took out some bits specific to my environment before posting) –

  2. Matty-uk

    Great that works.

    Only other thing I would suggest is to change the below line. That way the script does not ask you to press Y to confirm the shutdown.

    Shutdown-VMGuest -VM $MyVM
    Shutdown-VMGuest -VM $MyVM -Confirm:$false

  3. Pingback: Devs4Ops Resources | IT Should Just Work

Comments are closed.