How to stop non-responsive VM with PowerCLI

What do you do after trying to stop a VM that isn’t working. Either you and hope and pray that it will start reponding to vSphere commands, or you can Kill-VM.

Function Kill-VM {
      <# .SYNOPSIS Kills a Virtual Machine. .DESCRIPTION Kills a virtual machine at the lowest level, use when Stop-VM fails. .PARAMETER VM The Virtual Machine to Kill. .PARAMETER KillType The type of kill operation to attempt. There are three types of VM kills that can be attempted: [soft, hard, force]. Users should always attempt 'soft' kills first, which will give the VMX process a chance to shutdown cleanly (like kill or kill -SIGTERM). If that does not work move to 'hard' kills which will shutdown the process immediately (like kill -9 or kill -SIGKILL). 'force' should be used as a last resort attempt to kill the VM. If all three fail then a reboot is required. .EXAMPLE PS C:\> Kill-VM -VM (Get-VM VM1) -KillType soft
 
      .EXAMPLE
         PS C:\> Get-VM VM* | Kill-VM
 
      .EXAMPLE
         PS C:\> Get-VM VM* | Kill-VM -KillType hard
   #>
   param (
      [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
      $VM, $KillType
   )
   PROCESS {
      if ($VM.PowerState -eq "PoweredOff") {
         Write-Host "$($VM.Name) is already Powered Off"
      } Else {
         $esxcli = Get-EsxCli -vmhost ($VM.VMHost)
         $WorldID = ($esxcli.vm.process.list() | Where { $_.DisplayName -eq $VM.Name}).WorldID
         if (-not $KillType) {
            $KillType = "soft"
         }
         $result = $esxcli.vm.process.kill($KillType, $WorldID)
         if ($result -eq "true"){
            Write-Host "$($VM.Name) killed via a $KillType kill"
         } Else {
            $result
         }
      }
   }
}

I find this script on the internet and I have integrated into my host profile for PowerShell. Now it is a simple command to kill a non-responsive VM.

Get-VM $VMName | Kill-VM -KillType Soft

Or

Get-VM $VMName | Kill-VM -Killtype Hard

This script was found from Virtu-Al.net

– Stuart

4 thoughts on “How to stop non-responsive VM with PowerCLI”

  1. Thanks for this! I’ve been following you for a while, but haven’t needed something until now.

    I just had a VM hanging in limbo that claimed it didn’t even have Tools installed. Even so, after running this, it instantly powered off. It came back up flawlessly, and I’m back up and running.

    Cheers,
    Carlos

Leave a Reply

Your email address will not be published. Required fields are marked *