Hyper-V PowerShell script to move virtual machines and put host in maintenance mode

A buddy of mine asked if I could find or write a PowerShell script that moves all virtual machines from a Hyper-V host and put the host in some sort of maintenance mode so that the moved virtual machines will not be moved back by the High Availability feature of the Hyper-V cluster.

I found some scripts online, but none of them did what I wanted to accomplish.
After some trial-and-error, this is the script that I found to do the trick Glimlach

$argumentslength = $args.length
$expectedargumentslength = 2
$manual = "Use this script by executing: HostMaintenance.ps1 "
if ($argumentslength -ne $expectedargumentslength)
{
  write-warning $manual; break
}
function MoveVM($vmobj, $hostobj)
{
  $hostrating = get-vmhostrating -vmhost $hostobj -vm $vmobj
  $orderedrating = $hostrating | sort-object rating –descending
  Write-Output $orderedrating
  $targethost = $null
  if ($orderedrating -is [Array])
  {
    if ($orderedrating[0].Rating -ne 0)
    {
      $targethost = $orderedrating[0].VMhost
    }
  }
  else
  {
    if ($orderedrating.Rating -ne 0)
    {
      $targethost = $orderedrating.VMHost
    }
  }
  if ($targethost -ne $null)
  {
    write-warning "Moving the Virtual Machine named $vmobj to host $targethost"
    $targetvm = move-vm -VM $vmobj -vmhost $targethost -Path $targethost.VMPaths[0] –RunAsynchronously
  }
  else
  {
    Write-Warning "There is no host available for the Virtual Machine named $vmobj and it will not be moved. Please free a host and run the script again!"
  }
}
$vmmserver = $args[0]
$c = get-vmmserver -ComputerName $vmmserver
$vms = Get-VM
$hostname = $args[1]
$VMHost = Get-VMHost -ComputerName $hostname
$AllHosts = Get-VMHost

$VMHost | Set-VMHost -MaintenanceHost $true

foreach ($VM in $VMHost.VMs)
{
MoveVM $VM $AllHosts
}

2 comments

  1. Josh says:

    Any suggestions on how to import the proper libraries? Import-Module or Add-PSSnapin, etc.?

  2. Jeff Wouters says:

    Josh: Howto import a module http://msdn.microsoft.com/en-us/library/windows/desktop/dd745033(v=vs.85).aspx
    And the will need the one for SCVMM, which is installed with the SCVMM Management Console.

Leave a Reply

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