#VMWare Killing Stuck, or Hung tasks with #Powershell #PowerCLI

Recently I ran into an issue where a Powered Off VM was stuck in a vMotion host migration for over 3 days. I assume that the VM was powered off during the migration, which is what caused it to hang. Afterwards two backup job snapshot tasks were also in queue on top of the migration task.

I spent about 10-15 minutes in the GUI trying to find how to kill or stop this task, unsuccessfully. The only option I could find was to right click on the active migration task, and click "cancel," which rendered ZERO results.

The task in the task list also shows that it was coming off my ESXi 46 host, but when checking manually with PowerCLI, 46 did not show any tasks associated with my problematic VM. This is why in the code below I pulled in get-vmhost into a variable, and then setup a loop to look for the VM name in the tasks lists on each host. This led me to show the destination host was "49" and actually had the tasks I was wanting to kill.

Below is how I solved the issue with Powershell / PowerCLI. It will prompt the user to enter 3 things.

  • The vCenter where the task is stuck.
  • The VM name.
  • The Killtype you wish to apply to the task. "soft, hard, or force."

Here is the code snippit:

function killvm-tasks {
$viserver = $(read-host "Enter vCenter Server")
connect-viserver $viserver | out-null
$vname = $(read-host "Enter the VM name")
$killtype = $(read-host "Enter Killtype:  soft, hard, or force")
$hosts = get-vmhost
foreach ($box in $hosts){
	$vmhost = get-esxcli -vmhost $box.Name
	$processes = $vmhost.vm.process.list()
	foreach ($process in $processes){
	    if ($process.Displayname -eq $vname){
			$vmhost.vm.process.kill($killtype, $process.WorldID)