Use WMI to create a VM with PowerShell

By | 2017-12-17

A function to create a new Hyper-V virtual machine using WMI, with the ability to create the VM on a remote host. Also allows for specifiying the target location.

function New-HyperVVM {  param (
   [string]$Hypervhost = "localhost",
   [string]$Vm = "VM Courtesy of PowerShell",
   [string]$location = "C:\MyVirtualMachines\$vm"
   )
 $wmiClassString = "\\" + $Hypervhost + "\root\virtualization:Msvm_VirtualSystemGlobalSettingData"
 $wmiclass = [WMIClass]$wmiClassString
 $newVSGlobalSettingData = $wmiClass.CreateInstance()
 $newVSGlobalSettingData.psbase.Properties.Item("ExternalDataRoot").value = $location
 $newVSGlobalSettingData.psbase.Properties.Item("ElementName").value = $Vm
 $VSManagementService = gwmi MSVM_VirtualSystemManagementService -namespace "root\virtualization" -ComputerName $Hypervhost
 $GlobalSettings  = $newVSGlobalSettingData.psbase.GetText(1)
 $VSManagementService.DefineVirtualSystem($GlobalSettings, $ResourceSettings)
}

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.