Search Tools Links Login

Use WMI to create a VM with PowerShell


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)
}

About this post

Posted: 2017-12-17
By: ASchneider
Viewed: 865 times

Categories

Scripting

Hyper-V

Powershell

Windows

PowerShell Code Cache

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.