Hyper-V How To: Create a VM using Script

Some friends here on the Hyper-V team shared a PowerShell 2.0 script for creating a VM:

# Create a VM

    [string]$vmName = $(throw “Must supply a virtual machine name”)

# Get a new instance of Msvm_VirtualSystemGlobalSettingData
$vsgsdClass = [wmiclass]”root\virtualization:Msvm_VirtualSystemGlobalSettingData”
$vsgsd = $vsgsdClass.CreateInstance()
$vsgsd.ElementName = $vmName

# Get the managment service and define the system from the embedded instance
$vmms = gwmi -namespace root\virtualization Msvm_VirtualSystemManagementService

$result = $vmms.DefineVirtualSystem($vsgsd.GetText(1))

if($result.ReturnValue -eq 4096){
    # A Job was started, and can be tracked using its Msvm_Job instance
    $job = [wmi]$result.Job
    # Wait for job to finish
    while($job.jobstate -lt 7){$job.get()}
    # Return the Job’s error code
    return $job.ErrorCode
# Otherwise, the method completed
return $result.ReturnValue


For more info on how to use PS cmdlets see: http://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/index.mspx

See also James O’Neil’s New and improved PowerShell Library for Hyper-V. Now with more functions and… documentation!

For all 35 sample Hyper-V PS1 scripts in a zipfile, go to: Hyper-V PowerShell Example Scripts.zip-download

Comments (2)

  1. Kenneth Cheung says:

    This seems sort of primitive to do workflow automation, especially in comparison to VMWARE Orchestrator in VSPHERE. I’d be interested to see what is coming down the pipe for a hyper v automation workflow engine.

    —- Ken

    uptime software will be at VMworld 2009 in San Fran this year, please feel free to drop by for a chat in person. We have a very cool VMworld promo, as we are giving away more than $80k of up.time 5 IT Systems Management software at the booth. http://www.uptimesoftware.com/VMworld-2009.php

  2. Um, check these out for a less "primitive" solution:

    PowerShell Management Library for Hyper-V at http://pshyperv.codeplex.com/

    The Official Scripting Guys Forum (click the Hyper-V tag) at http://social.technet.microsoft.com/Forums/en-US/ITCG/threads/

    SCVMM at http://technet.microsoft.com/en-us/scvmm/default.aspx