Change properties of VMs as they are imported on Hyper-V

Change properties of VMs as they are imported on Hyper-V

Q. How can I easily import a number of VMs from a folder structure and automatically fix any core problems such as wrong switch name or more cores than supported on the system?

A. The script below will import all VMs found in a folder path and will automatically fix the switch to a new switch it creates (you could change this to use an existing switch you have) and also solves and issues if the VM has more cores than supported on the box by changing to 4.

import-module hyper-v 

$VMRootPath = 'C:\Workshop'

New-VMSwitch -Name "InternalSwitch" `
  -SwitchType Internal

$VMXMLFiles = Get-ChildItem -recurse $VMrootPath\*.xml

foreach($VMXMLFile in $VMXMLFiles)
 #Import will fail as switch name is different
 $report = Compare-VM -Path $VMXMLFile
 foreach($incompatibility in $report.Incompatibilities)
  if($incompatibility.MessageId -eq '33012') #Switch problem
   Write-Output "Binding to different VMSwitch"
   $incompatibility.Source | Connect-VMNetworkAdapter -SwitchName "InternalSwitch"
  if($incompatibility.MessageId -eq '25014') #Cannot restore saved state
   Write-Output "Removing saved state"
   $Report.VM | Remove-VMSavedState 
  if($incompatibility.MessageId -eq '14420') #Too many cores
   Write-Output "Changing number of cores to 4"
   $Report.VM | Remove-VMSavedState #Need to remove saved state to change cores
   $Report.VM | Set-VM -ProcessorCount 4
 $newvm = import-vm -CompatibilityReport $report
 start-vm -VM $newvm


Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.