Sample Job-Related Scripts

You can experiment with the Windows PowerShell scripts that are described in this topic to learn how to script the following job-related tasks in a Virtual Machine Manager environment:

  • Enable Virtual Machine Remote Control (VMRC) on all host servers on which it is currently disabled.
  • List all virtual machines on which Virtual Manager Additions is not yet installed.
  • Track the progress of a running job.

EnableVMRC.ps1

Virtual Machine Remote Control is a feature of Microsoft Virtual Server 2005 that lets a VMRC client connect to an instance of Virtual Server to access that server's virtual machines. VMRC lets users access their virtual machines remotely. In Virtual Machine Manager, you can enable, disable, or configure VMRC.

How EnableVMRC.ps1 Works

The EnableVMRC.ps1 script performs the following tasks:

  • Connects to the Virtual Machine Manager server.
  • Gets the objects for all virtual machine hosts, and stores the host objects in variable $VMHosts.
  • Filters for those hosts on which VMRC is not enabled. If any exist, the script enables the following functionality on those hosts:
    • The VMRC feature itself.
    • Multiple simultaneous VMRC connections. Enabling multiple simultaneous VMRC connections allows two or more VMRC connections to be established to the same virtual machine at the same time.

EnableVMRC.PS1 - Complete Script

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

# Filename:    EnableVMRC.ps1
# Description: Finds virtual machine hosts managed by Virtual Machine 
#              Manager on which VMRC is disabled and enables VMRC on 
#              those hosts.

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

####################################################################
# Connect to the Virtual Machine Manager server.
####################################################################
# Substitute the name of your VMM server and domain in this command:
$VMMServer = Get-VMMServer -ComputerName "VMMServer1.Contoso.com"

######################################################################
# Find all virtual machine hosts with VMRC disabled and enable VMRC. 
######################################################################

$VMHosts = @(Get-VMHost)
$VMHostsWithVMRCDisabled = @($VMHosts | where {$_.VMRCEnabled -eq $false})

if ($VMHostsWithVMRCDisabled.Count -ne 0)
{
    Write-Host -ForegroundColor Yellow "ENABLE VMRC"
}

foreach ($VMHost in $VMHostsWithVMRCDisabled)
{ 
    Write-Host "Enabling VMRC on host", $VMHost.Name, "..."
    $UpdatedVMHost = Set-VMHost -VMHost $VMHost -VMRCEnabled $true -VMRCMultipleConnectionsEnabled $true
} 

NeedVMAdditions.ps1

For any virtual machine to function well, you must install Virtual Machine Additions on the 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.

You can use the NeedVMAdditions.ps1 script to identify which virtual machines in your Virtual Machine Manager environment do not yet have Virtual Machine Additions installed.

If you find virtual machines that currently lack Virtual Machine Additions, you can copy the VMAdditions.iso file from Virtual Server 2005 (which is installed by default with Virtual Machine Manager) to a library share on a Virtual Machine Manager library server. The VMAdditions.iso file is in Windows Explorer at <C>:\Program Files\Microsoft Virtual Server\Virtual Machine Additions.

When a copy of the VMAdditions.iso file is in the Virtual Machine Manager library, you can install Virtual Machine Additions on a virtual machine by adding a virtual DVD drive to the virtual machine, connecting the virtual DVD drive to the VMAdditions.iso file, and then (after you connect to the virtual machine) running the Setup utility for Virtual Machine Additions from the virtual DVD drive.

See the script InstallVMAdditions.ps1 in the topic "Sample Scripts for Managing Virtual Machines" in this guide for an alternative method to identify virtual machines without Virtual Machine Additions. The alternative method also includes installing Virtual Manager Additions as part of the script.

How NeedVMAdditions.ps1 Works

The NeedVMAdditions.ps1 script performs the following tasks:

  • Connects to the Virtual Machine Manager server.
  • Retrieves the object for all virtual machines.
  • Filters for those virtual machines on which Virtual Machine Additions is not installed. If any exist, the script adds the string "Needs VM Additions" to the Custom10 property for those virtual machines.

NeedVMAdditions.ps1 - Complete Script

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

# Filename:    NeedVMAdditions.ps1
# Description: Finds virtual machines managed by Virtual Machine 
#              Manager on which VM Additions is not installed and sets 
#              the Custom10 property on those virtual machines to 
#              \"Needs VM Additions\"

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

####################################################################
# Connect to the Virtual Machine Manager server.
####################################################################
# Substitute the name of your VMM server and domain in this command:
$VMMServer = Get-VMMServer -ComputerName "VMMServer1.Contoso.com".

######################################################################
# Find all virtual machines without VM Additions. 
######################################################################

$VMs = @(Get-VM)
$VMsWithoutAdditions = @($VMs | where {$_.HasVMAdditions -eq $false})

if ($VMsWithoutAdditions -ne 0)
{
    Write-Host -ForegroundColor Yellow "UPDATE CUSTOM PROPERTY"
}

######################################################################
# Update the Custom10 property for each VM that needs VM Additions
######################################################################

foreach ($VM in $VMsWithoutAdditions)
{ 
    Write-Host "Setting Custom10 property as `"Needs VM Additions`" on VM", $VM.Name, "..."
    $UpdatedVM = Set-VM -VM $VM -Custom10 "Needs VM Additions"
}

TrackJobStatus.ps1

You can use the TrackJobStatus.ps1 script to monitor the progress of a Virtual Machine Manager job while you wait until the job is completed before you take further action.

How TrackJobStatus.ps1 Works

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

Define a Function that Enables the Use of VMRC to View a Virtual Machine

Virtual Machine Remote Control (VMRC) connects to an instance of Virtual Server, which runs on a Virtual Machine Manager host, and provides access to the virtual machines that are deployed on that host. The first set of commands in TrackJobStatus.ps1 defines a function that the script uses to enable using the VMRC application (VMRC.exe) for viewing a virtual machine that is deployed on a host:

  • The first command stores in variable $VMRC_String the URL to the VMRC server (the host) on which a virtual machine is deployed. The generic format for the URL is: VMRC://FullComputerName.com:PortNumber/VirtualMachineName. The default port number is 5900.

    Important

    The VMRC URL requires the full computer name rather than a fully qualified domain name (FQDN) because a physical server can have any number of FQDNs, but it has only one full computer name. You can view the full computer name on the Computer Name tab of System Properties for the computer.

  • The second command starts VMRC on the virtual machine and stores the resulting object in variable $VMRC_Process.

  • The last command tells the function to return program execution to the script and display the value of $VMRC_Process.

####################################################################
# Define a function that enables using VMRC.exe to view a VM.
####################################################################
function Start-VMRCProcess ($VM)
{
   # Store in a variable the URL to the VMRC server that hosts a VM:
   $VMRC_String = "VMRC://"+$VM.VMHost.Name+":"+ $VM.VMHost.VMRCPort +"/"+$VM.Name

   # Start VMRC on the VM deployed on the host and store the resulting 
   # object in a variable.
   $VMRC_Process = [Diagnostics.Process]::Start("C:\Program Files\Microsoft System Center Virtual Machine Manager 2007\bin\VMRC.exe", $VMRC_String)

   # Return execution to the script and display $VMRC_Process.
   return $VMRC_Process; 
}

Connect to the Virtual Machine Manager Server

The first command connects to the Virtual Machine Manager server and retrieves the object that represents the server from the Virtual Machine Manager database.

####################################################################
# Connect to the Virtual Machine Manager server.
####################################################################
# Substitute the name of your VMM server and domain in this command:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"

Define Variables for TrackJobStatus.ps1

The next set of commands in TrackJobStatus.ps1 defines a set of variables to be used to create the job:

####################################################################
# Define variables.
####################################################################
# Substitute the name of your host server and domain in this command:
$VMHost = Get-VMHost -ComputerName "VMHost01.Contoso.com"

# Substitute the path to your .vmx file in this command:
$LegacyVM = "E:\VMWare\Windows Server 2003 Enterprise Edition (Dynamic)\Windows Server 2003 Enterprise Edition.vmx"
$Memory=256

# Substitute the name of your virtual machine for VM01 in this command:
$VMName = "VM01"
$VMPath = $VMHost.VMPaths[0]

Start a Job and Track the Progress

The next command in TrackJobStatus.ps1 creates a job and tracks the progress of that job. The job that the script tracks is the creation of a new Virtual Server–based virtual machine that is managed by Virtual Machine Manager from a VMware-based virtual machine.

The script uses the RunAsynchronously parameter to return control to the shell immediately and uses the JobVariable parameter to track job progress and to store a record of its progress in the variable named Job. For JobVariable, you do not use the dollar sign ($) when the job variable is created, but you do use the dollar sign when the job variable is invoked.

####################################################################
# Run a VMM cmdlet that creates a job - in this example script, the 
# cmdlet is New-V2V, so the job is the creation of a new VM from an 
# existing VMware VM.
####################################################################
$VM = New-V2V -VMXPath $LegacyVM -VMHost $VMHost -Name $VMName -Path $VMPath -Memory $Memory -Runasynchronously -Jobvariable "Job"

Track Job Progress

The next commands in TrackJobStatus.ps1 track the status of the job while it runs:

####################################################################
# Track the status of the running job.
####################################################################
$JobNameString = $Job.CmdletName+" "+$Job.ResultName

# Loop while the job is running, writing progress using current step 
# and progress values from the job.
while ($job.status -eq "Running")  

{    
Write-Progress -Activity "$JobNameString" -Status $Job.CurrentStep -PercentComplete $Job.ProgressValue; 

Start-Sleep -seconds 5;  
}

Take Action Based on Job Success or Failure

The next commands in TrackJobStatus.ps1 determine what actions to take after the job is completed, based on job termination status:

  • If the job fails, display an error message.
  • If the job succeeds, display a message informing the user that the job was completed successfully, and the user can use the resulting object. In the following example, if the job succeeds, the newly converted virtual machine is created and started, and then the Start-VMRCProcess function that was defined earlier lets you view the new virtual machine.
####################################################################
# After job completes, take action based on job completion status:
#     If the job fails, display error information.
#     Otherwise, display a message that the VM is ready. 
####################################################################
Write-Host $JobNameString $Job.Status

if ($Job.Status -eq "Failed")

{
# JOB FAILED
Write-Output $Job.ErrorInfo;
}
else
{
# JOB SUCCEEDED
Write-Host "$VM is ready."

# Start the virtual machine.
Start-VM $VM;
# Use the Start-VMRCProcess function defined above to view the 
# virtual machine.
Start-VMRCProcess $VM;
}

TrackJobStatus.ps1 - Complete Script

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

# Filename:     TrackJobStatus.ps1
# Description:  How to monitor the progress of a job while 
#               waiting until the job completes before you take 
#               further action.

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

####################################################################
# Define a function that enables using VMRC.exe to view a VM.
####################################################################
function Start-VMRCProcess ($VM)
{
   # Store in a variable the URL to the VMRC server that hosts a VM:
   $VMRC_String = "VMRC://"+$VM.VMHost.Name+":"+ $VM.VMHost.VMRCPort +"/"+$VM.Name

   # Start VMRC on the VM deployed on the host and store the resulting 
   # object in a variable.
   $VMRC_Process = [Diagnostics.Process]::Start("C:\Program Files\Microsoft System Center Virtual Machine Manager 2007\bin\VMRC.exe", $VMRC_String)

   # Return execution to the script and display $VMRC_Process
   return $VMRC_Process; 
}

####################################################################
# Connect to the Virtual Machine Manager server.
####################################################################
# Substitute the name of your VMM server and domain in this command:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"

####################################################################
# Define variables.
####################################################################
# Substitute the name of your host server and domain in this command:
$VMHost = Get-VMHost -ComputerName "VMHost01.Contoso.com"

# Substitute the path to your .vmx file in this command:
$LegacyVM = "E:\VMWare\Windows Server 2003 Enterprise Edition (Dynamic)\Windows Server 2003 Enterprise Edition.vmx"
$Memory=256

# Substitute the name of your virtual machine for VM01 in this command:
$VMName = "VM01"
$VMPath = $VMHost.VMPaths[0]

####################################################################
# Run a VMM cmdlet that creates a job - in this example script, the 
# cmdlet is New-V2V, so the job is the creation of a new VM from an 
# existing VMware VM.
####################################################################
$VM = New-V2V -VMXPath $LegacyVM -VMHost $VMHost -Name $VMName -Path $VMPath -Memory $Memory -Runasynchronously -Jobvariable "Job"

####################################################################
# Track the status of the running job.
####################################################################
$JobNameString = $Job.CmdletName+" "+$Job.ResultName

# Loop while the job is running, writing progress using current step 
# and progress values from the job.
while ($job.status -eq "Running")  

{    
Write-Progress -Activity "$JobNameString" -Status $Job.CurrentStep -PercentComplete $Job.ProgressValue; 

Start-Sleep -seconds 5;  
}

####################################################################
# After job completes, take action based on job completion status:
#     If the job fails, display error information.
#     Otherwise, display a message that the VM is ready. 
####################################################################
Write-Host $JobNameString $Job.Status

if ($Job.Status -eq "Failed")

{
# JOB FAILED
Write-Output $Job.ErrorInfo;
}
else
{
# JOB SUCCEEDED
Write-Host "$VM is ready."

# Start the virtual machine.
Start-VM $VM;
# Use the Start-VMRCProcess function defined above to view the 
# virtual machine.
Start-VMRCProcess $VM;
}