Export (0) Print
Expand All

CreateNewVMs.ps1

Updated: February 12, 2009

Applies To: Virtual Machine Manager 2008, Virtual Machine Manager 2008 R2, Virtual Machine Manager 2008 R2 SP1

You can use the following script to create multiple virtual machines when you do not have an existing template. This script does the following tasks:

  • Creates a hardware profile.

  • Creates a guest operating system profile.

  • Creates a template by using the profiles and a virtual hard disk that was prepared by the Sysprep tool.

  • Creates the specified number of virtual machines from the template, and deploys the virtual machines on the most suitable host, as determined by the host ratings.

  • Displays progress messages as the virtual machines are being created, and displays a final status message.

To create virtual machines using a template that you already created, see CreateNewVMsFromTemplate.ps1.

Disclaimer

# Filename:    CreateNewVMs.ps1
# Description: Creates a System Center Virtual Machine Manager (VMM)-based 
#              hardware profile and operating system profile. Then, the 
#              script creates a template by using the profiles with a   
#              virtual hard disk that was prepared by the Sysprep tool. 
#              The template is used to create the specified number of 
#              virtual machines which are then deployed on the most  
#              suitable host. The script displays progress messages 
#              for each task, and it displays a final status message.


# Connect to the VMM server.

$VMMServer = Get-VMMServer "VMMServer1.Contoso.com"

# Define the variables.
# Define the hardware profile parameters.

$HWProfileName = "HwCfgWith1DVD1NIC512MBRam"
$MemoryInMB = 512

# Define the guest operating system profile parameters.
# Replace the "X" strings with your product key.

$OSProfileName = "Win2K8EntProfile"
$ProductKey = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"
$GuestOS = get-operatingsystem -VMMServer $VMMServer| where {$_.Name -eq "64-bit edition of Windows Server 2008 Enterprise"}

# Provide an administrator password for the guest operating system profile.
# The password is obtained by using the Get-Credential cmdlet so 
# that the password does not need to be stored in the script or in 
# the answer file in plain text.

$AdminCreds = Get-Credential -credential Administrator

$FullName = "VMMUser"
$Workgroup = "VMWorkgroup"
$AnswerFilePath = "\\LibraryServer1.Contoso.com\MSSCVMMLibrary\Scripts\Unattend.xml"

# Define the template parameters.

$TemplateName = "Win2K8EntTemplate"
$SysPrepVHD = "\\LibraryServer1.Contoso.com\MSSCVMMLibrary\VHDs\Win2008-RTM-Sysprep.vhd"

# Define the virtual machine parameters.
# Specify the number of virtual machines that you want to create.

$VMName = "VMN_"
$NumVMs = 2

# Create a hardware profile.

$HWProfileJobGroup = [System.Guid]::NewGuid()
New-VirtualDVDDrive -Bus 1 -Lun 0 -JobGroup $HWProfileJobGroup
New-VirtualNetworkAdapter -EthernetAddressType Dynamic -NoConnection -JobGroup $HWProfileJobGroup
$HWProfile = New-HardwareProfile -Name $HWProfileName -MemoryMB $MemoryInMB -JobGroup $HWProfileJobGroup

# Create a guest operating system profile from the Unattend.xml script.

$Script = Get-Script | where {$_.SharePath -eq $AnswerFilePath}
$OSProfile = New-GuestOSProfile -Name $OSProfileName -Desc $OSProfileName -ComputerName "*" -ProductKey $ProductKey -TimeZone 004 -FullName $FullName -JoinWorkgroup $Workgroup -AdminPasswordCredential $AdminCreds -AnswerFile $Script -OperatingSystem $GuestOS

# Create a template from the Win2K8 virtual hard drive that was prepared by the Sysprep  
# tool, from the hardware profile, and from the guest operating system profile.

$TemplateJobGroup = [System.Guid]::NewGuid()
$Win2K8VHD = Get-VirtualHardDisk -VMMServer $VMMServer | where {$_.Location -eq $SysPrepVHD}
New-VirtualDiskDrive -VMMServer $VMMServer -IDE -Bus 0 -Lun 0 -JobGroup $TemplateJobGroup -VirtualHardDisk $Win2K8VHD
$VMTemplate = New-Template -Name $TemplateName -Description $TemplateName -HardwareProfile $HWProfile -GuestOSProfile $OSProfile -JobGroup $TemplateJobGroup

# Create the specified number of virtual machines from the template and 
# determine the best host on which to deploy each virtual machine.

# Create a random number to use later to create a unique name for each
# virtual machine.
$Random = (New-Object Random)

# Get all of the hosts.
$VMHosts = Get-VMHost

# Get the size of the virtual hard drive.
$DiskSizeGB = $Win2K8VHD.Size /1024 /1024 /1024

# Create variable arrays in which to store tasks and virtual machines.

$NewVMTasks = [System.Array]::CreateInstance("Microsoft.SystemCenter.VirtualMachineManager.Task", $NumVMs)
$NewVMs = [System.Array]::CreateInstance("Microsoft.SystemCenter.VirtualMachineManager.VM", $NumVMs)

$i=0

#Create the virtual machines.

While($NumVMs -gt 0)
{
   # Generate a unique virtual machine name.
   $Random = New-Object System.Random
   $VMRnd = $Random.next()
   $VMName = $VMName+$VMRnd
   If ($VMName.length -gt "15") { $VMName = $VMName.Substring(0,14) }

   # Get and sort the host ratings for all the hosts in the host group.
   $HostRatings = @(Get-VMHostRating -DiskSpaceGB $DiskSizeGB -Template $VMTemplate -VMHost $VMHosts -VMName $VMName | where { $_.Rating -gt 0 } | Sort-Object -property Rating -descending)

   If($HostRatings.Count -eq "0") { throw "No hosts meet the requirements." }

   # Check for a virtual network. 
   # If there is a virtual network, set the hardware profile to connect to it.

   $network = @(Get-VirtualNetwork | where{$_.VMHost -eq $VMHost})[0]
   if($network -ne $empty) 
   {
      Set-VirtualNetworkAdapter -VirtualNetwork $network -VirtualNetworkAdapter $HWProfile.VirtualNetworkAdapters[0]
   }

   # If there is at least one host that will support the virtual machine,
   # create the virtual machine on the highest-rated host.

   If ($HostRatings.Count -ne 0)
   {

      $VMHost = $HostRatings[0].VMHost
      $VMPath = $HostRatings[0].VMHost.VMPaths[0]

      #Generate a new job group.
      $VMJobGroup = [System.Guid]::NewGuid()

      Get-Template -VMMServer $VMMServer | where { $_.Name -eq $VMTemplate }

      # Create the virtual machine.
      $NewVMs[$i] = New-VM -Template $VMTemplate -Name $VMName -Description "Virtual machine created from a script" -VMHost $VMHost -Path $VMPath -JobGroup $VMJobGroup -RunAsynchronously -Owner "CONTOSO\Phyllis" -ComputerName $VMName -OrgName "" -TimeZone 4 -JoinWorkgroup "WORKGROUP"  -AnswerFile $null -RunAsSystem -StartAction NeverAutoTurnOnVM -StopAction SaveVM 
      
      $NewVMTasks[$i] = $NewVms[$i].MostRecentTask
      $i = $i +1

   }

   $NumVMs = $NumVMs -1
}

# Wait for all of the tasks to complete, and provide a progress 
# message about each task.

$Done = 0
while($Done -eq 0)
{ 
    $Done = 1
    Start-Sleep -seconds 10
    ForEach($Task in $NewVMTasks)
    {
        Write-Host $Task.ResultName "VM creation" $Task.Status $Task.Progress Complete $Task.ErrorInfo.Problem 
        Write-Host "##############################"
        Write-Host ""
        if($Task.Status -eq "Running")
        {
           $Done = 0
        }
    }
}

# Display the results.

ForEach($Task in $NewVMTasks)
{
    Write-Host $Task.ResultName "VM creation " $Task.Status "Start time" $Task.StartTime.DateTime "End time" $Task.EndTime.DateTime $Task.ErrorInfo.Problem 
    Write-Host "##############################"
    Write-Host ""
}  
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft