Export (0) Print
Expand All

Sample Scripts for Managing Virtual Machines

You can experiment with the Windows PowerShell scripts that are described in this topic to learn how to script the following tasks for virtual machines that are managed by Virtual Machine Manager:

  • Automate creating multiple virtual machines.
  • Install Virtual Machine Additions.
  • Configure virtual machines in a two-node cluster.
  • Adapt a script that is generated by an Administrator Console wizard to create virtual machines.

AutomateNewVMCreation.ps1

You can use the AutomateNewVMCreation.ps1 script to automate the creation of a specified number of virtual machines.

How AutomateNewVMCreation.ps1 Works

The following sections explain each part of the script AutomateNewVMCreation.ps1.

Define Variables for AutomateNewVMCreation.ps1

The first set of commands in AutomateNewVMCreation.ps1 defines variables that the script uses to create multiple virtual machines.

####################################################################
# Define variables
####################################################################

Each set of variables is described in the following sections.

Define a variable for the Virtual Machine Manager server

When you define a string variable for the name of your Virtual Machine Manager server, you can use "localhost" if the server is the local computer. However, if the Virtual Machine Manager server is remote, you must specify the fully qualified domain name (FQDN) of the server, such as ServerName.DomainName.com.

# Define a string variable for your VMM server.
$VMMServer = "localhost"

Define hardware profile parameters

A Virtual Machine Manager hardware profile stores hardware configuration information for a virtual machine. The script uses the hardware profile as one of the building blocks from which it creates a template; it then uses the template to create virtual machines. The script uses the parameters that are defined in the hardware profile to set:

  • The hardware profile name.
  • The amount of memory that is available to virtual machines that are created by the script.

Parameters that are not specified use the default settings. For more information about hardware profiles, type Get-Help New-HardwareProfile at the command prompt.

# Define hardware profile parameters.
$HWProfileName = "HwCfgWith1DVD1NIC512MBRam"
$MemoryInMB = 512

Define guest operating-system profile parameters

A Virtual Machine Manager guest operating system profile provides the operating system for a virtual machine. The script uses the guest operating-system profile as one of the building blocks from which it creates a template; it then uses the template to create virtual machines. The script uses the parameters that are defined in the guest operating-system profile to set:

  • The guest operating-system profile name. A guest operating system is the operating system on a virtual machine, in contrast to a host operating system on the physical host computer on which one or more virtual machines are deployed.
  • The product key. Substitute your 25-digit product key number for the X's.
  • A password for the local Administrator account on the virtual machine.
  • The full name. The name or role of the person in whose name the virtual machine, created by using this profile, is registered. This is the name that appears on the General tab of a computer's System Properties page under Registered to.
  • The name of the workgroup to which the virtual machine belongs.
  • The path to the SysPrep.inf text file, which is the unattended answer file that the System Preparation tool, SysPrep.exe, uses to automate deployment of Windows operating systems on multiple computers.

Parameters that are not specified use the default settings.

For more information about guest operating-system profiles, type Get-Help New-GuestOSProfile at the command prompt. For more information about SysPrep.inf and SysPrep.exe, see Microsoft Knowledge Base article 302577, "How to use the Sysprep tool to automate successful deployment of Windows XP" at http://go.microsoft.com/fwlink/?LinkId=104720.

# Define guest OS profile parameters.
$OSProfileName = "Win2K3R2Profile"
$ProductKey = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"
$AdminPassword = "!!123abc"
$FullName = "VMMUser"
$Workgroup = "VMWorkgroup"
$SysPrepScriptPath = "\\LibraryServer1.Contoso.com\MSSCVMMLibrary\Scripts\SysPrep.inf"

Define template parameters

A Virtual Machine Manager virtual machine template, which stores hardware configuration and guest operating-system information, can be used repeatedly to create new virtual machines. After creating a hardware profile and a guest operating-system profile, the script constructs a template using the parameters defined in the profiles and from a sysprepped virtual hard disk that contains the Windows Server 2003 R2 operating system. The example script assumes that you have a sysprepped virtual hard disk called ENU-W2003-Std-R2-Sysprep.vhd. The script uses the parameters that are define in the template to set:

  • The name of the template.
  • The path to the virtual hard disk that contains the sysprepped virtual hard disk.

Parameters that are not specified use the default settings. For more information about virtual machine templates, type Get-Help New-Template at the command prompt.

# Define template parameters.
$TemplateName = "Win2K3R2Template"
$SysPrepVHDPath = "\\LibraryServer1.Contoso.com\MSSCVMMLibrary\VHDs\ENU-W2003-Std-R2-Sysprep.vhd"

Define virtual machine parameters

After creating a template, the script uses it to create a virtual machine. The script uses the parameters that are defined in the template to set:

  • A unique name for each virtual machine.
  • The path to a second virtual hard disk that the script adds to each virtual machine. The example script assumes that you have a virtual hard disk called BaseDisk20GB.vhd. This virtual hard disk is other than the sysprepped virtual hard disk that is used to provide the operating system to the virtual machines.
  • The number of virtual machines that are created by the script.
# Define virtual machine parameters.
$VMName = "VMN_"
$VMAdditionalVhdDiskPath = "\\LibraryServer1.Contoso.com\MSSCVMMLibrary\VHDs\BaseDisk20GB.vhd"
$NumVMs = 2

Define a Function That Creates a Secure Credential

The next set of commands in the script AutomateNewVMCreation.ps1 defines a function that the script uses to create a Windows PowerShell credential object (PSCredential object) by prompting the user for the user name and password that are required to join a computer to the domain.

####################################################################
# Define a function to create a PSCredential object.
####################################################################
function SecurePass {
param([string]$User, [string]$Password)
    $SPassword = New-Object System.Security.SecureString
    for ($i=0; $i -lt $Password.Length; $i++) {
        $SPassword.AppendChar($Password[$i])
    }
    New-Object System.Management.Automation.PSCredential $User,$SPassword
}

Connect to the Virtual Machine Manager Server

The next command in the script AutomateNewVMCreation.ps1 connects to the Virtual Machine Manager server so that subsequent commands can access objects in the Virtual Machine Manager database. The command uses a value stored earlier in $VMMServer (in this case, localhost) to retrieve the server object from the Virtual Machine Manager library and store the server object in variable $C.

In this command, the parameter -ComputerName (as in: Get-VMMServer ComputerName $VMMServer) is assumed.

####################################################################
# Connect to the Virtual Machine Manager server.
####################################################################
$C = Get-VMMServer $VMMServer

Create a Hardware Profile

The next set of commands in the script AutomateNewVMCreation.ps1 creates a hardware profile with one DVD drive and one network adapter, and it sets the amount of memory to 512 RAM ($MemoryInMB was defined as 512 earlier).

Specifically, these commands perform the following tasks:

  • The first command generates a GUID and stores the GUID in variable $HWProfileJobGroup. The job group ID functions as an identifier that groups subsequent commands in this set of commands into a single job group.
  • The second command creates a virtual DVD drive but uses the JobGroup parameter to specify that the DVD drive is not created until just before the New-HardwareProfile cmdlet (in the last command) runs. Specifying Bus 1 and LUN 0 attaches the virtual DVD drive to Secondary Channel (0) on the IDE bus.
  • The third command creates a virtual network adapter but uses the JobGroup parameter to specify that the network adapter is not created until just before the New-HardwareProfile cmdlet (in the last command) runs. This command sets the Ethernet address type to dynamic and uses the -NoConnection parameter to specify that the network adapter is not currently connected to a network.
  • The last command creates and names a hardware profile. It specifies that the amount of memory on the host that a virtual machine (created by using this hardware profile) uses is 512 MB, and stores the hardware profile object in variable $HWProfile. Before the New-HardwareProfile cmdlet creates the hardware profile, the JobGroup parameter in this final command executes all of the preceding cmdlets that specify the same JobGroup GUID. When New-VirtualDVDDrive and New-VirtualNetworkAdapter run, the resulting objects that are created are automatically associated with the new hardware profile.

Later, the script incorporates this hardware profile into the virtual machine template that is created by the New-Template cmdlet.

####################################################################
# 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

The next set of commands in the script AutomateNewVMCreation.ps1 creates a guest operating system profile by performing the following tasks:

  • The first command uses the Virtual Machine Manager cmdlet Get-Script to get all objects from the Virtual Machine Manager database that represent scripts and then uses the pipeline operator (|) to pass the objects to the standard Windows PowerShell cmdlet, Where-Object. Where-Object (whose alias is where) selects the object that represents the SysPrep.inf text file (which SysPrep.exe uses to automate deployment of Windows operating systems on multiple computers) and stores that object in variable $Script.
  • The second command uses the SecurePass function, which was defined earlier, to create a secure password for the local Administrator account.
  • The last command performs the following tasks:
    • Creates and names a guest operating-system profile.
    • Specifies a description.
    • Sets the computer name to be randomly generated (indicated by the asterisk “*”).
    • Specifies a product key.
    • Specifies the role (VMMUser) of the person in whose name a virtual machine, created by using this profile, is registered.
    • Specifies that any virtual machine that is created by using this profile is joined to the workgroup called VMWorkGroup.
    • Provides the secure password, which was generated earlier by the SecurePass function.
    • Specifies the SysPrep.inf file to be used for any virtual machine that is created by using this profile.
    • Stores the guest operating-system profile object in variable $OSProfile.

Later, the script incorporates this guest operating-system profile into the virtual machine template that is created by the New-Template cmdlet.

####################################################################
# Create a guest OS profile from the SysPrep.inf script.
####################################################################
$Script = Get-Script | where {$_.SharePath -eq $SysPrepScriptPath}
$Cred = SecurePass "Administrator" $AdminPassword
$OSProfile = New-GuestOSProfile -Name $OSProfileName -Desc $OSProfileName -ComputerName "*" -ProductKey $ProductKey -FullName $FullName -JoinWorkgroup $Workgroup -AdminPasswordCredential $Cred -SysPrepFile $Script

Create a Template from a SysPrepped Virtual Hard Disk and from the Profiles

The next set of commands in the script AutomateNewVMCreation.ps1 constructs a template (used later in the script to create virtual machines) from the following components:

  • The hardware profile and the guest operating-system profile, which was created earlier.
  • A virtual hard disk that contains Windows Server 2003 R2, which has been prepared by the System Preparation Tool (Sysprep.exe).
    Note
    Sysprep.exe must be run on the virtual hard disk to ensure that each copy of the operating system is unique when you distribute it to multiple virtual machines.

    You can find Sysprep.exe on any Windows Server 2003 (or Windows XP Professional) operating-system CD. Navigate to the Support\Tools folder, and then open Deploy.cab. The local Administrator password on the sysprepped virtual hard disk must be blank.

Specifically, the commands in this set perform the following tasks:

  • The first command gets the object from the Virtual Machine Manager databases and stores the object in $Win2K3R2VHD. The object represents the sysprepped virtual hard disk that was stored earlier, with its path, in $SysPrepVHDPath.
  • The second command generates a GUID and stores the GUID in variable $TemplateJobGroup. The job group ID functions as an identifier that groups subsequent commands in this set of commands into a single job group.
  • The third command adds the virtual hard disk to the template (to be created in last step in this set of commands) but uses the JobGroup parameter to specify that the virtual hard disk is not attached until just before the New-Template cmdlet runs in the last step. Specifying Bus 0 and LUN 0 attaches the virtual hard disk to Primary Channel (0) on the IDE bus.
  • The last command performs the following tasks:
    • Creates and names the template.
    • Provides a description, which is the same as the template name.
    • Specifies that this template incorporates the hardware profile and guest operating-system profile that was created earlier.
    • Uses the JobGroup parameter to specify that any of the preceding commands that include variable $TemplateJobGroup will run before New-Template creates the new template. After Add-VirtualHardDisk (the only command preceding this command that includes $TemplateJobGroup) runs, the resulting virtual hard disk object that is created is automatically associated with the new template.

Next, the script uses this template to create the number of virtual machines that is specified in $NumVMs.

####################################################################
# Create a template from the Win2K3R2 sysprepped VHD, hardware 
# profile, and guest OS profile.
####################################################################
$Win2K3R2VHD = Get-VirtualHardDisk | where {$_.SharePath -eq $SysPrepVHDPath}
$TemplateJobGroup = [System.Guid]::NewGuid()
$Win2K3R2VHD | Add-VirtualHardDisk -Bus 0 -Lun 0 -IDE -JobGroup $TemplateJobGroup
$Template = New-Template -Name $TemplateName -Description $TemplateName -HardwareProfile $HWProfile -GuestOSProfile $OSProfile -JobGroup $TemplateJobGroup

Create the Virtual Machines from the Template, Add a Virtual Hard Disk, and Deploy Each Virtual Machine on a Host

The next set of commands in the script AutomateNewVMCreation.ps1 creates the specified number ($NumVMs) of virtual machines from the template that was created earlier, adds an additional virtual hard disk (which is not provided by the template) to each new virtual machine, and uses host ratings to determine the best host on which to deploy each virtual machine.

#####################################################################
# Create the specified number of VMs from the template (adding 
# another VHD) and determine the best host on which to deploy each VM.
#####################################################################

Each set of commands for this part of the script is described in the following sections.

Create a random number

The first command creates a random number that the script uses later to create a unique name for each virtual machine.

# Create a random number used later to create a unique name for a VM.
$Random = (New-Object Random)

Get the additional virtual hard disk

The second command retrieves the object from the Virtual Machine Manager database that represents the virtual hard disk called BaseDisk20GB.vhd, which is located on the specified share, and stores the virtual hard disk object in variable $VMAdditionalVhd.

# Get the object that represents BaseDisk20GB.vhd.
$VMAdditionalVhd = Get-VirtualHardDisk | where {$_.SharePath -eq $VMAdditionalVhdDiskPath}

Get all hosts

The third command retrieves the objects from the Virtual Machine Manager database that represent all hosts on which you can deploy virtual machines.

# Get the objects that represent all hosts.
$VMHosts = Get-VMHost

Calculate hard disk space on the host required by a virtual machine

The fourth command calculates the total amount of hard disk space that is required on the physical host by a virtual machine. In this example script, the disk size is the same for each virtual machine because the script uses the same template to create all virtual machines.

# Calculate the amount of hard disk space required on the physical 
# host by a VM. 
$DiskSizeGB = ($Win2K3R2VHD.Size + $VMAdditionalVhd.Size) /1024 /1024 /1024

Create arrays for tasks and virtual machines

The fifth command creates variable arrays in which to store:

  • Tasks. Objects that represent the tasks that the script runs as the script creates each virtual machine. $NumVMs indicates the size of the array.
  • VMs. Objects that represent each new virtual machine. $NumVMs indicates the size of the array.
# Create variable arrays in which to store tasks and VMS.
$NewVMTasks = [System.Array]::CreateInstance("Microsoft.SystemCenter.VirtualMachineManager.Task", $NumVMs)
$NewVMs = [System.Array]::CreateInstance("Microsoft.SystemCenter.VirtualMachineManager.VM", $NumVMs)

Create and deploy each virtual machine

The last command uses a while loop to create each virtual machine asynchronously. The loop performs the following tasks:

  • Generates a unique name for each virtual machine and stores the object that represents the new name in variable $NewVMName. Each name is prefixed with the contents of $VMName and includes a random number in the name.
  • Gets the placement rating for each host that meets the virtual machine requirements specified in the template, and sorts the hosts by placement rating. The rating indicates the suitability of a computer (or a set of computers in a host group) to serve as a host for a virtual machine with a specific hardware configuration.
  • Uses an if statement to create virtual machines on hosts whose rating is greater than zero:
    • The first command in the if statement stores the object for each host whose rating is greater than zero in variable $VMHost.
    • The second command in the if statement is the path to which each virtual machine is to be deployed on the hosts in variable $VMPath.
    • The third command in the if statement generates a GUID and stores the GUID in variable $NewVMJobGroup. The job group ID functions as an identifier that groups subsequent commands in this set of commands into a single job group..
    • The fourth command in the if statement uses the pipeline operator (|) to pass the contents of $VMAdditionalVhd to the Add-VirtualHardDisk cmdlet, which adds a virtual hard disk to the virtual machine but uses the JobGroup parameter to specify that the virtual hard disk is not attached until just before the New-VM cmdlet runs in the next step. Specifying -Bus 0 -Lun 1 attaches the virtual hard disk to the Primary Channel (1) on the built-in IDE bus.
    • The fifth command in the if statement provides a name and description for a new virtual machine; creates the new virtual machine based on the settings specified in the template; deploys the new virtual machine on a host at the specified path; uses the -RunAsynchronously parameter returns control to the shell immediately ,before the command is completed; and starts the virtual machine. Before the New-VM cmdlet creates the virtual machine, the JobGroup parameter in this command runs all of the preceding cmdlets that specify the same JobGroup GUID. After Add-VirtualHardDisk (the only command preceding this command that includes $NewVMJobGroup) runs, the resulting virtual hard disk object that is created is automatically associated with the new virtual machine. This command stores the object that represents the new virtual machine in variable array $NewVMs.
    • The sixth command in the if statement stores the object that represents the most recent task in the variable array $NewVMTasks.
    • The last command in the if statement increments the index.
  • The next command in the while statement ($NumVMs - 1) subtracts one from the number of virtual machines to be created by the while loop.
  • The last command in the while statement uses the standard Windows PowerShell Start-Sleep cmdlet to suspend execution of the while statement for five seconds to allow time for the operation to finish before the while loop repeats.
$i = 0
# Loop that creates each VM asynchronously.
while($NumVMs -gt 0)
{
    # Generate a unique VM name.
    $VMRnd = $Random.next()
    $NewVMName = $VMName+$VMRnd

    # Get the ratings for each host and sort the hosts by ratings.
    $Ratings = @(Get-VMHostRating -Template $Template -VMHost $VMHosts -DiskSpaceGB $DiskSizeGB -VMName $NewVMName | where { $_.Rating -gt 0} | Sort-Object -property Rating -descending)

    if ($Ratings.Count -gt 0) 
    {
       $VMHost = $Ratings[0].VMHost
       $VMPath = $Ratings[0].VMHost.VMPaths[0]

       # Create a new VM from the template and add an additional VHD
       # to the VM.
       $NewVMJobGroup = [System.Guid]::NewGuid()
       $VMAdditionalVhd | Add-VirtualHardDisk -Bus 0 -Lun 1 -IDE -JobGroup $NewVMJobGroup
       $NewVMs[$i] = New-VM -Template $Template -Name $NewVMName -Description $NewVMName -VMHost $VMHost -Path $VMPath -RunAsynchronously -StartVM -JobGroup $NewVMJobGroup
       $NewVMTasks[$i] = $NewVMs[$i].MostRecentTask
       $i = $i + 1
   }
   $NumVMs = $NumVMs - 1
   Start-Sleep -seconds 5

}

Display Progress Messages

The next set of commands in the script AutomateNewVMCreation.ps1 displays a progress message about each task as the script creates each new virtual machine.

####################################################################
# 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 5
    ForEach($Task in $NewVMTasks)
    {
        echo "##############################"
        echo $Task.ResultName "VM creation" $Task.Status $Task.Progress Complete $Task.ErrorInfo.Problem 
        echo "##############################"
        echo ""
        if($Task.Status -eq "Running")
        {
           $done = 0
        }
    }
}

Display Results Messages

The final set of commands in the script AutomateNewVMCreation.ps1 displays a message indicating the result as the script creates each new virtual machine.

####################################################################
# Display results.
####################################################################
ForEach($Task in $NewVMTasks)
{
    echo "##############################"
    echo $Task.ResultName "VM creation " $Task.Status "Start time" $Task.StartTime.DateTime "End time" $Task.EndTime.DateTime $Task.ErrorInfo.Problem 
    echo "##############################"
    echo ""
}  

AutomateNewVMCreation.ps1 - Complete Script

Copy the following complete version of AutomateNewVMCreation.ps1 into a Notepad file, and save it as AutomateNewVMCreation.ps1.

# Filename:    AutomateNewVMCreation.ps1
# Description: Create a System Center Virtual Machine Manager-based 
#              hardware profile and operating-system profile; use 
#              these profiles and a sysprepped VHD to create a 
#              template; use the template to create 'n' number of 
#              virtual machines, adding an additional VHD to each
#              new VM; and deploy each virtual machine on the most 
#              suitable host. Display progress messages for each task 
#              and display a final status message for attempt to
#              create a virtual machine.

# DISCLAIMER:
# Copyright © Microsoft Corporation. All rights reserved. This 
# script is made available to you without any express, implied or 
# statutory warranty, not even the implied warranty of 
# merchantability or fitness for a particular purpose, or the 
# warranty of title or non-infringement. The entire risk of the 
# use or the results from the use of this script remains with you.

####################################################################
# Define variables
####################################################################
# Define a string variable for your VMM server.
$VMMServer = "localhost"

# Define hardware profile parameters.
$HWProfileName = "HwCfgWith1DVD1NIC512MBRam"
$MemoryInMB = 512

# Define guest OS profile parameters.
$OSProfileName = "Win2K3R2Profile"
$ProductKey = "C938K-6CHYF-2K8VH-FX94R-XVQ2J"
$AdminPassword = "!!123abc"
$FullName = "VMMUser"
$Workgroup = "VMWorkgroup"
$SysPrepScriptPath = "\\LibraryServer1.Contoso.com\MSSCVMMLibrary\Scripts\SysPrep.inf"

# Define template parameters.
$TemplateName = "Win2K3R2Template"
$SysPrepVHDPath = "\\LibraryServer1.Contoso.com\MSSCVMMLibrary\VHDs\ENU-W2003-Std-R2-Sysprep.vhd"

# Define VM parameters.
$VMName = "VMN_"
$VMAdditionalVhdDiskPath = "\\LibraryServer1.Contoso.com\MSSCVMMLibrary\VHDs\BaseDisk20GB.vhd"
$NumVMs = 2

####################################################################
# Define a function to create a PSCredential object.
####################################################################
function SecurePass {
param([string]$User, [string]$Password)
    $SPassword = New-Object System.Security.SecureString
    for ($i=0; $i -lt $Password.Length; $i++) {
        $SPassword.AppendChar($Password[$i])
    }
    New-Object System.Management.Automation.PSCredential $User,$SPassword
}

####################################################################
# Connect to the Virtual Machine Manager server.
####################################################################
$C = Get-VMMServer $VMMServer

####################################################################
# 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 OS profile from the SysPrep.inf script.
####################################################################
$Script = Get-Script | where {$_.SharePath -eq $SysPrepScriptPath}
$Cred = SecurePass "Administrator" $AdminPassword
$OSProfile = New-GuestOSProfile -Name $OSProfileName -Desc $OSProfileName -ComputerName "*" -ProductKey $ProductKey -FullName $FullName -JoinWorkgroup $Workgroup -AdminPasswordCredential $Cred -SysPrepFile $Script

####################################################################
# Create a template from the Win2K3R2 sysprepped VHD, hardware 
# profile, and guest OS profile.
####################################################################
$Win2K3R2VHD = Get-VirtualHardDisk | where {$_.SharePath -eq $SysPrepVHDPath}
$TemplateJobGroup = [System.Guid]::NewGuid()
$Win2K3R2VHD | Add-VirtualHardDisk -Bus 0 -Lun 0 -IDE -JobGroup $TemplateJobGroup
$Template = New-Template -Name $TemplateName -Description $TemplateName -HardwareProfile $HWProfile -GuestOSProfile $OSProfile -JobGroup $TemplateJobGroup

#####################################################################
# Create the specified number of VMs from the template (adding 
# another VHD) and determine the best host on which to deploy each VM.
#####################################################################
# Create a random number used later to create a unique name for a VM.
$Random = (New-Object Random)

# Get the object that represents BaseDisk20GB.vhd.
$VMAdditionalVhd = Get-VirtualHardDisk | where {$_.SharePath -eq $VMAdditionalVhdDiskPath}

# Get the objects that represent all hosts.
$VMHosts = Get-VMHost

# Calculate the amount of hard disk space required on the physical 
# host by a VM. 
$DiskSizeGB = ($Win2K3R2VHD.Size + $VMAdditionalVhd.Size) /1024 /1024 /1024

# Create variable arrays in which to store tasks and VMS.
$NewVMTasks = [System.Array]::CreateInstance("Microsoft.SystemCenter.VirtualMachineManager.Task", $NumVMs)
$NewVMs = [System.Array]::CreateInstance("Microsoft.SystemCenter.VirtualMachineManager.VM", $NumVMs)

$i = 0
# Loop that creates each VM asynchronously.
while($NumVMs -gt 0)
{
    # Generate a unique VM name.
    $VMRnd = $Random.next()
    $NewVMName = $VMName+$VMRnd

    # Get the ratings for each host and sort the hosts by ratings.
    $Ratings = @(Get-VMHostRating -Template $Template -VMHost $VMHosts -DiskSpaceGB $DiskSizeGB -VMName $NewVMName | where { $_.Rating -gt 0} | Sort-Object -property Rating -descending)

    if ($Ratings.Count -gt 0) 
    {
       $VMHost = $Ratings[0].VMHost
       $VMPath = $Ratings[0].VMHost.VMPaths[0]

       # Create a new VM from the template and add an additional VHD
       # to the VM.
       $NewVMJobGroup = [System.Guid]::NewGuid()
       $VMAdditionalVhd | Add-VirtualHardDisk -Bus 0 -Lun 1 -IDE -JobGroup $NewVMJobGroup
       $NewVMs[$i] = New-VM -Template $Template -Name $NewVMName -Description $NewVMName -VMHost $VMHost -Path $VMPath -RunAsynchronously -StartVM -JobGroup $NewVMJobGroup
       $NewVMTasks[$i] = $NewVMs[$i].MostRecentTask
       $i = $i + 1
   }
   $NumVMs = $NumVMs - 1
   Start-Sleep -seconds 5
}

####################################################################
# 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 5
    ForEach($Task in $NewVMTasks)
    {
        echo "##############################"
        echo $Task.ResultName "VM creation" $Task.Status $Task.Progress Complete $Task.ErrorInfo.Problem 
        echo "##############################"
        echo ""
        if($Task.Status -eq "Running")
        {
           $done = 0
        }
    }
}

####################################################################
# Display results.
####################################################################
ForEach($Task in $NewVMTasks)
{
    echo "##############################"
    echo $Task.ResultName "VM creation " $Task.Status "Start time" $Task.StartTime.DateTime "End time" $Task.EndTime.DateTime $Task.ErrorInfo.Problem 
    echo "##############################"
    echo ""
}  

InstallVMAdditions.ps1

You can use the InstallVMAdditions.ps1 script to install Virtual Machine Additions on virtual machines that are managed by Virtual Machine Manager.

For any virtual machine to function well, you must install Virtual Machine Additions on that virtual machine. Virtual Machine Additions, which is provided by Virtual Server 2005, improves the performance of the guest operating system, enables the free movement of the mouse between the virtual machine window and the host operating system, optimizes video drivers, and supports time synchronization.

For a related script that identifies which virtual machines in your Virtual Machine Manager environment do not yet have Virtual Machine Additions installed, see NeedVMAdditions.ps1 in the topic, "Sample Job-Related Scripts" in this guide.

How InstallVMAdditions.ps1 Works

The following sections explain each part of the script InstallVMAdditions.ps1.

Define Variables for InstallVMAdditions.ps1

The first commands in InstallVMAdditions.ps1 define variables that the script uses to install Virtual Machine Additions. As indicated in the comment introducing $LinkIso, you have the option to set $LinkIso to $TRUE or $FALSE depending on whether you want to link to the VMAdditions.iso or copy it onto the virtual machine.

####################################################################
# Define variables.
####################################################################
$VMMServer = "localhost"
$VMNameToInstallVMAdditions = "VM01"
# If you want to link to VMAdditons.iso in the Virtual Machine Manager 
# library, set $LinkIso to $TRUE; alternatively, if you want to copy 
# VMAdditions.iso to the VM, set $LinkIso to $FALSE.
$LinkIso = $FALSE

Connect to the Virtual Machine Manager Server

The next command in InstallVMAdditions.ps1connects to the Virtual Machine Manager server so that subsequent commands can access objects in the Virtual Machine Manager database.

####################################################################
# Connect to the Virtual Machine Manager server.
####################################################################
$C = Get-VMMServer $VMMServer

Get the Virtual Machine on Which to Install Virtual Machine Additions.

The next command in InstallVMAdditions.ps1 retrieves the object that represents the virtual machine whose name was stored earlier in variable $VMNameToInstallVMAdditions.

####################################################################
# Get the VM on which you want to install VM Additions.
####################################################################
$VM = Get-VM | where {$_.Name -eq $VMNameToInstallVMAdditions}

Install Virtual Machine Additions or Display an Error Message

The next set of commands in InstallVMAdditions.ps1 performs a series of nested tests to determine whether it is possible to install Virtual Machine Additions and, if any test fails, displays an error message indicating what you need to do to solve the problem.

  • Is the virtual machine installed on a host?
    • If yes, continue to the next question.
    • If not, the script ends and displays a message indicating that it cannot install Virtual Machine Additions because the virtual machine is currently stored in the library. You must deploy the virtual machine on a host and then run the script again. For more information, type the following command at the command prompt:
      Get Help Move-VM -detailed
  • Does the virtual machine have at least one virtual DVD drive?
    • If yes, the script does the following:
      Stores host object. Stores the object that represents the host on which this virtual machine is deployed in variable $VmHost.
      Stores ISO name string. Uses the command segment $VmHost.VirtualizationStack to determine which version of Virtual Server is running on the host (because Virtual Machine Additions varies depending on the Virtual Server version); concatenates the Virtual Server version with the string " VMAdditions"; and then stores the resulting name in variable $Isoname. The example assumes that Virtual Server version plus " VMAdditions" is the naming convention that is used to identify different versions of Virtual Machine Additions.
      Gets ISO object. Gets the object that represents the Virtual Machine Additions .iso file in variable $VmAdditions.Iso.
      Continue to the next question.
    • If not, the script ends and displays a message indicating that it cannot install Virtual Machine Additions because no virtual DVD drive exists on the virtual machine. You must configure a virtual DVD drive for this virtual machine and then run the script again. For more information, type the following command at the command prompt:
      Get-Help New-VirtualDVDDrive -detailed
  • Does at least one Virtual Machine Additions .iso file (of the correct version) exist in the library?
    • If yes, continue to the next question.
    • If not, the script ends and displays a message indicating that it cannot install Virtual Machine Additions because no Virtual Machine Additions .iso file exists in the Virtual Machine Manager library. You must add an .iso file for Virtual Machine Additions to a Virtual Machine Manager library share and then run the script again.
      After you add the .iso file to a library share, the Virtual Machine Manager refresher automatically scans the share, discovers the new .iso file, and adds an object that represents the .iso file to the library catalog. Alternatively, you can use the Refresh-LibraryShare cmdlet to refresh the library share immediately.
      For more information, type the following command at the command prompt:
      Get-Help Refresh-LibraryShare -detailed
      Note
      You can copy the VMAdditions.iso file from Microsoft Virtual Server 2005, which is installed by default with Virtual Machine Manager. You can find the VMAdditions.iso file in Windows Explorer at <C>:\Program Files\Microsoft Virtual Server\Virtual Machine Additions.

  • Do you want to link to or copy the .iso file?
    • Link to? If you have set $LinkIso to $TRUE, the script uses the pipeline operator (|) to pass the first virtual DVD drive (indicated by [0]) on the virtual machine to the Set-VirtualDVDDrive cmdlet, which links to the Virtual Machine Additions .iso file in the library.
      The command segment -Bus $VM.VirtualDVDDrives[0].Bus -Lun $VM.VirtualDVDDrives[0].Lun must be specified when changing the attached .iso file of a virtual DVD drive. In this case, the script does not modify where the virtual DVD drive is attached, so it simply sets the -Bus and -Lun parameters to the current Bus and Lun settings. Finally, the script stores the resulting object in variable $DVDDrive in case you want to use this variable later on.
    • Copy? If you have set $LinkIso to $FALSE, the script uses the pipeline operator (|) to pass the first virtual DVD drive (indicated by [0]) on the virtual machine to the Set-VirtualDVDDrive cmdlet, which copies the Virtual Machine Additions .iso file onto the virtual machine.
      The command segment -Bus $VM.VirtualDVDDrives[0].Bus -Lun $VM.VirtualDVDDrives[0].Lun must be specified when changing the attached .iso file of a virtual DVD drive. In this case, the script does not modify where the virtual DVD drive is attached, so it simply sets the -Bus and -Lun parameters to the current Bus and Lun settings. Finally, the script stores the resulting object in variable $DVDDrive in case you want to use this variable later on.
      Note
      The second command omits the -Link parameter but uses the $FALSE value specified earlier. By default, if -Link is omitted, the Set-VirtualDVDDrive cmdlet copies a file rather than linking to it.

    • Link to or Copy—same result: After the script either runs the command to link to the Virtual Machine Additions .iso file in the library or runs the command to copy the .iso file to the virtual machine, the script displays a message indicating that the Virtual Machine Additions .iso file is now attached to the virtual machine and requests the user to start the virtual machine and install Virtual Machine Additions from the virtual DVD drive.
####################################################################
# Install VM Additions or (if not possible) display an error message.
####################################################################
if($VM.HostType -eq "VMHost")
{
    if($VM.VirtualDVDDrives.Count -gt 0)
    {
      $VmHost = $VM.VMHost
      # The segment$VmHost.VirtualizationStack returns the version 
      # of Virtual Server running on this host.
      $IsoName = $VmHost.VirtualizationStack +" VMAdditions"
      $VmAdditionIso = Get-ISO | where {$_.Name -eq $IsoName}
      if($Null -ne $VmAdditionIso)
        {
          if($LinkIso -eq $TRUE)
          {
              $DvdDrive = $VM.VirtualDVDDrives[0] | set-VirtualDVDDrive -ISO $VmAdditionIso -Link -Bus $VM.VirtualDVDDrives[0].Bus -Lun $VM.VirtualDVDDrives[0].Lun
          }
          else
          {
              $DvdDrive = $VM.VirtualDVDDrives[0] | set-VirtualDVDDrive -ISO $VmAdditionIso -Bus $VM.VirtualDVDDrives[0].Bus -Lun $VM.VirtualDVDDrives[0].Lun
          }
          echo "Attached " $VmAdditionIso.Name " to VM" $VM.Name " Please start the vm if not running and install additions from dvddrive"
      }
      else
      {
           echo "Can't install vmadditions on VM " $VM.Name " as $IsoName ISO not present, please add it to library and retry"
      }
  }
  else
  {
      echo "Can't install vmadditions on VM " $VM.Name " has no VirtualDVDDrives present, please add a dvddrive and retry"
       
  }
}
else
{
    echo "Can't install vmadditions on VM " $VM.Name " in library, please deploy to host and retry"
}

InstallVMAdditions.ps1 - Complete Script

Copy the following complete version of InstallVMAdditions.ps1 into a Notepad file, and save it as InstallVMAdditions.ps1.

# Filename:    InstallVMAdditions.ps1
# Description: Create a System Center Virtual Machine Manager-based 
#              hardware profile and operating-system profile; use 
#              these profiles and a sysprepped VHD to create a 
#              template; use the template to create 'n' number of 
#              virtual machines, adding an additional VHD to each
#              new VM; and deploy each virtual machine on the most 
#              suitable host. Display progress messages for each task 
#              and display a final status message for attempt to
#              create a virtual machine.

# DISCLAIMER:
# Copyright © Microsoft Corporation. All rights reserved. This 
# script is made available to you without any express, implied or 
# statutory warranty, not even the implied warranty of 
# merchantability or fitness for a particular purpose, or the 
# warranty of title or non-infringement. The entire risk of the 
# use or the results from the use of this script remains with you.

####################################################################
# Define variables
####################################################################
$VMMServer = "localhost"
$VMNameToInstallVMAdditions = "VM01"
# If you want to link to VMAdditons.iso in the Virtual Machine Manager 
# library, set $LinkIso to $TRUE; alternatively, if you want to copy 
# VMAdditions.iso to the VM, set $LinkIso to $FALSE.
$LinkIso = $FALSE

####################################################################
# Connect to the Virtual Machine Manager server.
####################################################################
$C = Get-VMMServer $VMMServer

####################################################################
# Get the VM on which you want to install VM Additions.
####################################################################
$VM = Get-VM | where {$_.Name -eq $VMNameToInstallVMAdditions}

####################################################################
# Install VM Additions or (if not possible) display an error message.
####################################################################

if($VM.HostType -eq "VMHost")
{
    if($VM.VirtualDVDDrives.Count -gt 0)
    {
      $VmHost = $VM.VMHost
      # The segment$VmHost.VirtualizationStack returns the version 
      # of Virtual Server running on this host
      $IsoName = $VmHost.VirtualizationStack +" VMAdditions"
      $VmAdditionIso = Get-ISO | where {$_.Name -eq $IsoName}
      if($Null -ne $VmAdditionIso)
        {
          if($LinkIso -eq $TRUE)
          {
              $DvdDrive = $VM.VirtualDVDDrives[0] | set-VirtualDVDDrive -ISO $VmAdditionIso -Link -Bus $VM.VirtualDVDDrives[0].Bus -Lun $VM.VirtualDVDDrives[0].Lun
          }
          else
          {
              $DvdDrive = $VM.VirtualDVDDrives[0] | set-VirtualDVDDrive -ISO $VmAdditionIso -Bus $VM.VirtualDVDDrives[0].Bus -Lun $VM.VirtualDVDDrives[0].Lun
          }
          echo "Attached " $VmAdditionIso.Name " to VM" $VM.Name " Please start the vm if not running and install additions from dvddrive"
      }
      else
      {
           echo "Can't install vmadditions on VM " $VM.Name " as $IsoName ISO not present, please add it to library and retry"
      }
  }
  else
  {
      echo "Can't install vmadditions on VM " $VM.Name " has no VirtualDVDDrives present, please add a dvddrive and retry"
       
  }
}
else
{
    echo "Can't install vmadditions on VM " $VM.Name " in library, please deploy to host and retry"
}

ConfigureGuestCluster.ps1

Virtual Server 2005, on which Virtual Machine Manager is built, allows for two-node guest clusters with servers implemented as virtual machines connected to a virtual shared cluster storage device. A guest cluster supports availability of server resources and applications to clients in an environment where availability does not require hardware redundancy.

You can use the ConfigureGuestCluster.ps1 script to set up two virtual machines in a two-node server cluster.

How ConfigureGuestCluster.ps1Works

The following sections explain each part of the script ConfigureGuestCluster.ps1.

Define Variables for ConfigureGuestCluster.ps1

The first commands in ConfigureGuestCluster.ps1 define variables that the script uses to configure a quorum disk and shared disk when setting up virtual machines in a two-node guest cluster.

####################################################################
# Define variables
####################################################################
$VMMServer = "localhost"
$vmNode1Name = "VMN_1228156997"
$vmNode2Name = "VMN_1480103423"
$QuorumDiskSizeInGB = 3
$QuorumDiskName = "QuorumDisk"
$SharedDiskSizeInGB = 8
$SharedDiskName = "SharedDisk"

Connect to the Virtual Machine Manager Server

The next command in ConfigureGuestCluster.ps1 connects to the Virtual Machine Manager server so that subsequent commands can access objects in the Virtual Machine Manager database.

####################################################################
# Connect to the Virtual Machine Manager server.
####################################################################
$C = Get-VMMServer $VMMServer

Get the Virtual Machines to Configure as a Two-Node Cluster

The next two commands retrieve from the Virtual Machine Manager database the objects that represent the two virtual machines that you want to use in a two-node cluster and stores each virtual machine object in a variable.

####################################################################
# Get both virtual machine nodes.
####################################################################
$vmNode1 = Get-VM | where {$_.Name -eq $vmNode1Name}
$vmNode2 = Get-VM | where {$_.Name -eq $vmNode2Name}

Create Two Shared SCSI Adapters for the First Node

When you create the two-node cluster using virtual machines, you must create two shared SCSI adapters on each node. This set of commands creates two shared SCSI adapters on the first node.

Specifically, the set of commands in this section performs the following tasks:

  • The first command generates a GUID and stores the GUID in variable $JobGroup1. The job group ID functions as an identifier that groups subsequent commands in this set of commands into a single job group.
  • The second and third commands create two virtual SCSI adapters on the first virtual machine, but use the JobGroup parameter to specify that the virtual SCSI adapters are not created until the Set-VM cmdlet (in the last command) runs.
  • The fourth command passes the object that represents the first virtual machine to the Set-VM cmdlet, which runs the two preceding cmdlets that specify the same JobGroup GUID, so that the two virtual SCSI adapters are actually created in this step.
####################################################################
# Create two shared SCSI adapters on vmNode1.
####################################################################
$JobGroup1 = [System.Guid]::NewGuid()
New-VirtualSCSIAdapter -Shared $True -JobGroup $JobGroup1 
New-VirtualSCSIAdapter -Shared $True -JobGroup $JobGroup1
$vmNode1 | Set-VM -JobGroup $JobGroup1

Create Two Shared SCSI Adapters for the Second Node

This set of commands creates two shared SCSI adapters on the second node.

####################################################################
# Create two shared SCSI adapters on vmNode2.
####################################################################
$JobGroup2 = [System.Guid]::NewGuid()
New-VirtualSCSIAdapter -Shared $True -JobGroup $JobGroup2 
New-VirtualSCSIAdapter -Shared $True -JobGroup $JobGroup2
$vmNode2 | Set-VM -JobGroup $JobGroup2

Create a Quorum Virtual Hard Disk on the First Node

A two-node guest cluster requires a quorum disk, which is a virtual hard disk that is used to store cluster configuration information. This command performs the following tasks:

  • Creates a fixed virtual hard disk on the first virtual machine.
  • Attaches it to the specified location (-Bus 0 -Lun 0) on the SCSI bus.
  • Names it QuorumDisk (the value of $QuorumDiskName).
  • Specifies that its size is 3 GB (the value of $QuorumDiskSizeInGB).
  • Stores the object that represents the new quorum virtual hard disk in variable $QuorumVHD.
####################################################################
# Create a new quorum VHD of size $QuorumDiskSizeInGB on $vmNode1.
####################################################################
$QuorumVHD = New-VirtualHardDisk -VM $vmNode1 -Fixed -SCSI -Bus 0 -Lun 0 -Filename $QuorumDiskName -Size $QuorumDiskSizeInGB

Create a Shared Virtual Hard Disk on the First Node

The command in this section, which creates a shared virtual hard disk on the first node, performs the following tasks:

  • Creates a fixed virtual hard disk on the first virtual machine.
  • Attaches it to the specified location (-Bus 1 -Lun 0) on the SCSI bus.
  • Names it SharedDisk (the value of $SharedDiskName).
  • Specifies that its size is 8 GB (the value of $SharedDiskSizeInGB).
  • Stores the object that represents the new shared virtual hard disk in variable $SharedVHD.
####################################################################
# Create a new shared VHD of size $SharedDiskSizeInGB on $vmNode1.
####################################################################
$SharedVHD = New-VirtualHardDisk -VM $vmNode1 -Fixed -SCSI -Bus 1 -Lun 0 -Filename $SharedDiskName -Size $SharedDiskSizeInGB

Attach the Quorum and Shared Virtual Hard Disks Created on the First Node to the Second Node

After creating the quorum virtual hard disk and the shared virtual hard disk on the virtual machine that acts as the first node in the two-node cluster, you must attach both of these virtual hard disks to the second node.

Specifically, the commands in this section perform the following tasks:

The first command adds the quorum virtual hard disk on the first node to the specified location (-Bus 0 -Lun 0) on the second node.

The second command adds the shared virtual hard disk on the first node to the specified location (-Bus 1 -Lun 0) on the second node.

####################################################################
# Attach QuorumVHD and SharedVHD created on $vmNode1 to $vmNode2
####################################################################
Add-VirtualHardDisk -VirtualHardDisk $QuorumVHD -SCSI -Bus 0 -Lun 0 -VM $vmNode2
Add-VirtualHardDisk -VirtualHardDisk $SharedVHD -SCSI -Bus 1 -Lun 0 -VM $vmNode2

ConfigureGuestCluster.ps1 - Complete Script

Copy the following complete version of ConfigureGuestCluster.ps1 into a Notepad file, and save it as ConfigureGuestCluster.ps1.

# Filename:    ConfigureGuestCluster.ps1
# Description: Configure two virtual machines managed by System Center
#              Virtual Machine Manager as a two-node cluster.

# DISCLAIMER:
# Copyright © Microsoft Corporation. All rights reserved. This 
# script is made available to you without any express, implied or 
# statutory warranty, not even the implied warranty of 
# merchantability or fitness for a particular purpose, or the 
# warranty of title or non-infringement. The entire risk of the 
# use or the results from the use of this script remains with you.
####################################################################
# Define variables
####################################################################
$VMMServer = "localhost"
$vmNode1Name = "VMN_1228156997"
$vmNode2Name = "VMN_1480103423"
$QuorumDiskSizeInGB = 3
$QuorumDiskName = "Quorumdisk"
$SharedDiskSizeInGB = 8
$SharedDiskName = "SharedDisk"

####################################################################
# Connect to the Virtual Machine Manager server.
####################################################################
$C = Get-VMMServer $VMMServer

####################################################################
# Get both virtual machine nodes.
####################################################################
$vmNode1 = Get-VM | where {$_.Name -eq $vmNode1Name}
$vmNode2 = Get-VM | where {$_.Name -eq $vmNode2Name}

####################################################################
# Create two shared SCSI adapters on vmNode1.
####################################################################
$JobGroup1 = [System.Guid]::NewGuid()
New-VirtualSCSIAdapter -Shared $True -JobGroup JobGroup1 
New-VirtualSCSIAdapter -Shared $True -JobGroup JobGroup1
$vmNode1 | Set-VM -JobGroup JobGroup1

####################################################################
# Create two shared SCSI adapters on vmNode2.
####################################################################
JobGroup2 = [System.Guid]::NewGuid()
New-VirtualSCSIAdapter -Shared $True -JobGroup JobGroup2 
New-VirtualSCSIAdapter -Shared $True -JobGroup JobGroup2
$vmNode2 | Set-VM -JobGroup JobGroup2

####################################################################
# Create a new quorum VHD of size $QuorumDiskSizeInGB on $vmNode1.
####################################################################
$QuorumVHD = New-VirtualHardDisk -VM $vmNode1 -Fixed -SCSI -Bus 0 -Lun 0 -Filename $QuorumDiskName -Size $QuorumDiskSizeInGB
####################################################################
# Create a new shared VHD of size $SharedDiskSizeInGB on $vmNode1.
####################################################################
$SharedVHD = New-VirtualHardDisk -VM $vmNode1 -Fixed -SCSI -Bus 1 -Lun 0 -Filename $SharedDiskName -Size $SharedDiskSizeInGB

####################################################################
# Attach QuorumVHD and SharedVHD created on $vmNode1 to $vmNode2.
####################################################################
Add-VirtualHardDisk -VirtualHardDisk $QuorumVHD -SCSI -Bus 0 -Lun 0 -VM $vmNode2
Add-VirtualHardDisk -VirtualHardDisk $SharedVHD -SCSI -Bus 1 -Lun 0 -VM $vmNode2

NewVMScriptFromWizard.ps1

You can create the Windows PowerShell script NewVMScriptFromWizard.ps1 that is described here to customize the script that is generated when you run the New virtual machine wizard in the Virtual Machine Manager Administrator Console. Although this example shows you how to modify a script that is generated by the New virtual machine wizard, you can make similar custom changes to scripts that are generated by other wizards.

How to Use View Script to Create a Reusable Script

Every wizard in Virtual Machine Manager contains a View Script button on the Summary page of the wizard. The View Script button opens a dialog box that displays the Windows PowerShell script that performs the same actions that were just performed by using the wizard. You can use these scripts as a starting point for creating custom scripts to automate tasks in your Virtual Machine Manager environment.

The View Script dialog box contains a script that creates a new virtual machine from a specific template. This example shows you how to customize that script to create a generic script. You can use this customized script repeatedly to create new virtual machines based on that template.

View Script Output Generated by the New Virtual Machine Wizard

The following is the original script that is generated by the New virtual machine wizard as it appears in the View Script dialog box. In this example, the wizard uses an existing template as the source object from which to create the virtual machine. The contents of the script vary depending on which options you choose when running the wizard.

Note
This example assumes that a virtual machine template named ''SampleTemplate" already exists. For information about how to create a new template for use in Virtual Machine Manager, type Get-Help New-Template -detailed at the Windows PowerShell - Virtual Machine Manager command prompt.

# --------------------------------------------------------------------
# New Virtual Machine Wizard Script
# --------------------------------------------------------------------
# Script generated on Sunday, July 01, 2007 6:12:14 PM by Virtual 
# Machine Manager
# 
# For additional help on cmdlet usage, type get-help <cmdlet name>.
# --------------------------------------------------------------------

Set-VirtualFloppyDrive -RunAsynchronously -VMMServer localhost -NoMedia -JobGroup e245e50f-6955-4837-8639-3e027c47b89f 

$CPUType = Get-ProcessorType -VMMServer localhost | where {$_.Name -eq "1-processor 1.20 GHz Athlon MP"}

New-HardwareProfile -VMMServer localhost -Owner "CONTOSO\Alex" -CPUType $CPUType -Name "Profilec331c4d2-bccb-46f7-8ff4-000abe429cb3" -Description "Profile used to create a VM/Template" -ProcessorCount 1 -MemoryMB 128 -ExpectedCPUUtilization 20 -DiskIO 0 -NetworkUtilization 10 -RelativeWeight 100 -JobGroup e245e50f-6955-4837-8639-3e027c47b89f 

$Template = Get-Template -VMMServer localhost | where {$_.Name -eq "SampleTemplate"}
$VMHost = Get-VMHost -VMMServer localhost | where {$_.Name -eq "VMHost01.Contoso.com"}
$HardwareProfile = Get-HardwareProfile -VMMServer localhost | where {$_.Name -eq "Profilec331c4d2-bccb-46f7-8ff4-000abe429cb3"}

New-VM -Template $Template -Name "SampleVM" -Description "" -VMHost $VMHost -Path "C:\Documents and Settings\All Users\Documents\Shared Virtual Machines\" -JobGroup 12eb89de-4b8d-4a14-9758-0b02215645a5 -RunAsynchronously -Owner "CONTOSO\Alex" -HardwareProfile $HardwareProfile -ComputerName "*" -FullName "User" -OrgName "Company" -ProductKey "12345-12345-12345-12345-12345" -TimeZone 4 -JoinWorkgroup "WORKGROUP"  -RunAsSystem -UseHardwareAssistedVirtualization $false -StopAction SaveVM 

Save the Script in View Script to a .ps1 File

Copy the script from the View Script dialog box and paste it into a new text file, as shown in the following procedure.

To save a script in the View Script dialog box as a .ps1 file
  1. Press CTRL+A to select all of the text in the View Script dialog box.

  2. Press CTRL+C to copy the script to the clipboard.

  3. Open Notepad and press CTRL+V to paste the script into the new text file.

  4. Save the file as “NewVMScriptFromWizard.ps1 ”.

    Important
    Make sure that you change the extension from .txt to .ps1.

Modify Input Options

Next, decide which options you want to provide as input to the script. In this example, allow users to modify the virtual machine name, the amount of memory, and the name of the destination host. In addition, set the computer name of the virtual machine to be the same as the virtual machine name.

Modify these input options by adding the following lines to the top of the script:

# --------------------------------------------------------------------
# Define script parameters and variables.
# --------------------------------------------------------------------
$VMName = $args[0]
$Memory = $args[1]
$VMHostName = $args[2]
$ComputerName = $VMName

These assignment statements tell the Windows PowerShell script to store the first argument that is passed into the script to the parameter $VMName, the second argument to $Memory, and the third argument to $VMHostName. Finally, variable $ComputerName is set to the same value as $VMName. Alternatively, you can set $ComputerName to $args[4].

Modify the Script to Use the New Variables

The last step is to modify the original script to use the parameters and variable that were defined in the preceding section. The following code segments make each of these changes.

Modify the New-HardwareProfile command

Modify the New-HardwareProfile command to use the new memory variable:

New-HardwareProfile -VMMServer localhost -Owner "CONTOSO\Alex" -CPUType $CPUType -Name "Profilec331c4d2-bccb-46f7-8ff4-000abe429cb3" -Description "Profile used to create a VM/Template" -ProcessorCount 1 -MemoryMB $Memory -ExpectedCPUUtilization 20 -DiskIO 0 -NetworkUtilization 10 -RelativeWeight 100 -JobGroup e245e50f-6955-4837-8639-3e027c47b89f 

Modify the Get-VMHost command

Modify the Get-VMHost command to use the new $VMHostName variable:

$VMHost = Get-VMHost -VMMServer localhost | where {$_.Name -eq $VMHostName}

Modify the New-VM command

Modify the New-VM command to use the new $VMName and $ComputerName variables:

New-VM -Template $Template -Name $VMName -Description "" -VMHost $VMHost -Path "C:\Documents and Settings\All Users\Documents\Shared Virtual Machines\" -JobGroup 12eb89de-4b8d-4a14-9758-0b02215645a5 -RunAsynchronously -Owner "CONTOSO\Alex" -HardwareProfile $HardwareProfile -ComputerName $ComputerName -FullName "User" -OrgName "Company" -ProductKey "12345-12345-12345-12345-12345" -TimeZone 4 -JoinWorkgroup "WORKGROUP" -RunAsSystem -UseHardwareAssistedVirtualization $false -StopAction SaveVM

NewVMScriptFromWizard.ps1 - Complete Script

Copy the following complete version of NewVMScriptFromWizard.ps1 into a Notepad file and save it as NewVMScriptFromWizard.ps1 . See the next section, "How to Use NewVMScriptFromWizard.ps1," in this topic for examples that show how to run this script.

Note
This example script assumes that a virtual machine template named ''SampleTemplate" already exists.

# Filename:    NewVMScriptFromWizard.ps1 
# Description: Create a new virtual machine based on a specific 
#              template. This script is derived from the System
#              Center Virtual Machine Manager output for View Script 
#              in the Administrator Console (GUI) output for View 
#              Script for the New virtual machine 
#              wizard.
   
# DISCLAIMER:
# Copyright (c) Microsoft Corporation. All rights reserved. This 
# script is made available to you without any express, implied or 
# statutory warranty, not even the implied warranty of 
# merchantability or fitness for a particular purpose, or the 
# warranty of title or non-infringement. The entire risk of the 
# use or the results from the use of this script remains with you.
####################################################################
# New Virtual Machine Wizard Script
####################################################################
# Script generated on Sunday, July 01, 2007 6:12:14 PM by Virtual 
# Machine Manager
# 
# For additional help on cmdlet usage, type get-help <cmdlet name>.
####################################################################

####################################################################
# Define script parameters and variables.
####################################################################
$VMName = $args[0]
$Memory = $args[1]
$VMHostName = $args[2]
$ComputerName = $VMName

####################################################################
# Create a virtual machine from a specific template.
####################################################################
Set-VirtualFloppyDrive -RunAsynchronously -VMMServer localhost -NoMedia -JobGroup e245e50f-6955-4837-8639-3e027c47b89f 

$CPUType = Get-ProcessorType -VMMServer localhost | where {$_.Name -eq "1-processor 1.20 GHz Athlon MP"}

New-HardwareProfile -VMMServer localhost -Owner "CONTOSO\Alex" -CPUType $CPUType -Name "Profilec331c4d2-bccb-46f7-8ff4-000abe429cb3" -Description "Profile used to create a VM/Template" -ProcessorCount 1 -MemoryMB $Memory -ExpectedCPUUtilization 20 -DiskIO 0 -NetworkUtilization 10 -RelativeWeight 100 -JobGroup e245e50f-6955-4837-8639-3e027c47b89f 

$Template = Get-Template -VMMServer localhost | where {$_.Name -eq "SampleTemplate"}
$VMHost = Get-VMHost -VMMServer localhost | where {$_.Name -eq $VMHostName}
$HardwareProfile = Get-HardwareProfile -VMMServer localhost | where {$_.Name -eq "Profilec331c4d2-bccb-46f7-8ff4-000abe429cb3"}

New-VM -Template $Template -Name $VMName -Description "" -VMHost $VMHost -Path "C:\Documents and Settings\All Users\Documents\Shared Virtual Machines\" -JobGroup 12eb89de-4b8d-4a14-9758-0b02215645a5 -RunAsynchronously -Owner "CONTOSO\Alex" -HardwareProfile $HardwareProfile -ComputerName $ComputerName -FullName "User" -OrgName "Company" -ProductKey "12345-12345-12345-12345-12345" -TimeZone 4 -JoinWorkgroup "WORKGROUP"  -RunAsSystem -UseHardwareAssistedVirtualization $false -StopAction SaveVM 

How to Use NewVMScriptFromWizard.ps1

You can run NewVMScriptFromWizard.ps1 in the Windows PowerShell - Virtual Machine Manager command shell to create new virtual machines, as shown in the following examples.

The first script creates a virtual machine named SampleVM01 with 256 MB of memory and places it on VMHost01:

PS C:\> NewVMScriptFromWizard.ps1 “SampleVM01” 256 “VMHost01”

The second script creates a virtual machine named SampleVM02 with 512 MB of memory and places it on VMHost02:

PS C:\> NewVMScriptFromWizard.ps1 “SampleVM02” 512 “VMHost02”
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft