Microsoft® System Center Virtual Machine Manager
System Center Virtual Machine Manager Scripting Guide
Microsoft Corporation
Published: October 2007
Abstract
Microsoft System Center Virtual Machine Manager 2007 is a server application for managing a large number of virtual machines and the servers that support those virtual machines. The Virtual Machine Manager command shell is built on Microsoft Windows PowerShell, an administrator-focused interactive shell and scripting language that is integrated into the Windows platform. This guide provides sample scripts illustrating how you can use Windows PowerShell scripting for centralized management of your physical and virtual system infrastructure.
Disclaimer: The sample scripts in this guide are not supported under any Microsoft standard support program or service. The sample scripts are provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages.
Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted in examples herein are fictitious. No association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.
© 2007 Microsoft Corporation. All rights reserved.
Microsoft, MS-DOS, Windows, Windows Server, Windows Vista, and Active Directory are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.
All other trademarks are property of their respective owners.
Contents
Windows PowerShell Scripting in Virtual Machine Manager
Microsoft System Center Virtual Machine Manager 2007 is a server application that you can use to manage a large number of virtual machines. This guide provides sample Microsoft Windows PowerShell scripts for Virtual Machine Manager. The sample scripts illustrate how you can manage the servers, virtual machines, and resources in your virtual environment.
The Virtual Machine Manager command shell is built on Microsoft Windows PowerShell, an administrator-focused, interactive command-line shell and scripting language that is integrated into the Windows operating system. Windows PowerShell and Virtual Machine Manager each provide commands, called cmdlets, that you can use separately to perform simple administrative tasks or together with other cmdlets or command-line elements to perform complex tasks. You can use Virtual Machine Manager cmdlets, and scripts that are created by using these cmdlets, as an alternative to (or in addition to) using the Administrator Console for centralized management of your physical and virtual system infrastructure.
Virtual Machine Manager uses a Microsoft SQL Server 2005 database to store Virtual Machine Manager objects that represent all entities in a Virtual Machine Manager environment. At minimum, a Virtual Machine Manager environment includes the following services, which you can install on a single server or on separate servers:
 Virtual Machine Manager server. A computer running Windows Server 2003 Service Pack 1 (SP1) that stores or accesses the SQL Server database, which contains Virtual Machine Manager objects.
 Host server. A computer running Microsoft Virtual Server 2005 R2 that functions as a host on which to deploy virtual machines.
 Library server. A computer running Windows Server 2003 with SP1 that stores a variety of resources for your virtual machine environment. Resources include hardware profiles, operating-system profiles, virtual machine templates, virtual hard disks (.vhd files), virtual floppy disks (.vfd files), ISO images (.iso files), and scripts. In addition, you can store virtual machines in the library that, currently, you do not want to deploy on a host.
ï‚· Web server. Optionally, Virtual Machine Manager also supports a Web server that acts as a Self-Service Portal for users who are allowed to create or manage their own virtual machines, or do both.
In Virtual Machine Manager, you can create virtual machines from a variety of sources, including from an existing stopped virtual machine that is already deployed on a host, from a virtual machine that is stored in the library, from a virtual hard disk, or from a template. Virtual Machine Manager supports physical-to-virtual machine conversion (P2V conversion) and virtual-to-virtual machine conversion (V2V conversion).
Understanding and experimenting with the sample scripts that are included in this guide provides a starting point for developing Windows PowerShell scripts that you can customize for use in your own Virtual Machine Manager environment.
Getting Started with PowerShell Scripting for VMM
Microsoft System Center Virtual Machine Manager 2007 is a server application that you can use to manage a large number of virtual machines. The Virtual Machine Manager server product includes the Windows PowerShell - Virtual Machine Manager command shell. You can use this command shell to manage virtual machine hosts, library servers, virtual machines, and other Virtual Machine Manager components interactively at the command line or by using task-based scripting.
The Windows PowerShell - Virtual Machine Manager command shell is built on Microsoft Windows PowerShell. Windows PowerShell is an administrator-focused interactive command shell and scripting language that is integrated into the Windows operating system.
The Virtual Machine Manager command shell includes not only all the standard Windows PowerShell cmdlets, but also provides a comprehensive set of cmdlets that are designed specifically for use with Virtual Machine Manager. You can use standard Windows PowerShell cmdlets with Virtual Machine Manager to create scripts. Windows PowerShell, including the Virtual Machine Manager command shell, supports programming constructions such as variable assignment, looping, conditional statements, and flow-control.
The sample scripts in this guide illustrate how you can use Windows PowerShell for centralized management of your physical and virtual infrastructure when that infrastructure is managed by Virtual Machine Manager. Experimenting with these scripts can help you understand how to create scripts that are useful in your own environment.
This topic includes the following sections:
ï‚· How Windows PowerShell Supports Scripting
ï‚· How to Create Simple Scripts
ï‚· How to Convert an Existing Cmdlet Help Example to a Script
ï‚· How to Use the Profile.ps1 Script to Run Your Scripts Without Typing the Path
ï‚· How WMI Enables Cross-Product Scripting
If you are not familiar with the relationship of Windows PowerShell and Virtual Machine Manager, see the introductory information in "Appendix A: About Windows PowerShell for Virtual Machine Manager." If you are not familiar with how to use standard Windows PowerShell or Virtual Machine Manager cmdlets interactively at the command line, see "Appendix B: Command-Line Tutorial."
How Windows PowerShell Supports Scripting
The following sections explain how to enable scripting in Windows PowerShell, which script extensions are used in Windows PowerShell, and how to run a script.
How to Enable Windows PowerShell Scripting
When you first open the Windows PowerShell command shell on a computer, you cannot immediately run a Windows PowerShell script because the default security policy does not allow running scripts. The Windows PowerShell security policy for scripting, called an execution policy, lets you determine whether scripts can run in your environment and whether they must include a digital signature. None of the execution policies in Windows PowerShell allow you to run a script by double-clicking its icon because that is a high-risk method of running a script.
The four execution policies that govern scripting in Windows PowerShell are:
ï‚· Restricted (default). Permits interactive commands only (no scripts).
ï‚· AllSigned. Permits scripts but requires a digital signature from a trusted publisher on all scripts and configuration files, including scripts that you write on the local computer.
ï‚· RemoteSigned. Permits scripts but requires a digital signature from a trusted publisher on all scripts and configuration files that are downloaded from the Internet, including e-mail. A digital signature is not required for scripts that you create on the local computer.
ï‚· Unrestricted. Permits scripts, including unsigned scripts.
The default Windows PowerShell execution policy is the Restricted policy, so you cannot run Windows PowerShell scripts unless you change to a less restrictive execution policy. The "How to Create a Windows PowerShell 'Hello World' Script" section later in this topic includes a procedure that demonstrates how to enable scripting on your server.
In addition, the following table lists Windows PowerShell Help topics that explain what you need to know about Windows PowerShell execution policies and how to change your policy so that you can run scripts.
How to find out more about Windows PowerShell execution policies
Type at the command prompt: |
Summary |
Get-Help about_Signing |
Describes Windows PowerShell execution policies and the varying levels of security that they provide. |
Get-Help Get-ExecutionPolicy |
Explains how to determine what your current scripting security policy is. |
Get-Help Set-ExecutionPolicy |
Explains how to change your current scripting security policy. |
How to Identify Windows PowerShell Script Extensions
In Windows PowerShell, most script files have a .ps1 file name extension. However, three types of file name extensions are available for script files:
ï‚· .ps1 extension—Windows PowerShell shell script. The extension for standard Windows PowerShell scripts—including those that you write as you experiment with the scripts included in this guide.
ï‚· .psc1 extension—Windows PowerShell console file. A special type of script file that defines the configuration of a specific Windows PowerShell console. For example:
ï‚· "Microsoft System Center Virtual Machine Manager 2007\bin\cli.psc1" is the Windows PowerShell console file for Virtual Machine Manager.
ï‚· "Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Console.psc1" is the Windows PowerShell console file for System Center Operations Manager.
For more information about Windows PowerShell consoles, type "Get-Help Export-Console" at the command prompt.
ï‚· .ps1xml extension—Windows PowerShell format and type definitions. These types of script files, in the Windows PowerShell home directory (at <C>:\WINDOWS\system32\windowspowershell\v1.0), provide a mechanism for extending the .NET Framework type system. For more information, type "Get-Help about_Types" at the command prompt.
How To Run a Windows PowerShell Script
You can use any of the following methods to run a Windows PowerShell script. In all cases you must indicate the full path with the name of the script even if you are working in the directory where the script is located.
ï‚· Use the Invoke-Expression cmdlet to run a script. For example:
Invoke-Expression C:\Scripts\<ScriptName>.ps1
ï‚· Use double quotation marks for any paths that include spaces. For example:
Invoke-Expression "C:\My Scripts\<ScriptName>.ps1"
ï‚· Use the ampersand to run a script. For example:
& C:\Scripts\<ScriptName>.ps1
ï‚· Specify only the path to the script. For example:
C:\Scripts\<ScriptName>.ps1
ï‚· Specify only the path to the script and omit the extension. For example:
C:\Scripts\<ScriptName>
ï‚· Use the dot backslash (.\) characters as a shorthand to indicate the local directory. For example:
.\ <ScriptName>.ps1
Important
You must indicate the full path with the name of the script even if you are working in the directory where the script is located—unless you create a special script called Profile.ps1 and configure it to enable you to run scripts without typing the path. For more information, see the "How to Enable Scripts to Run Without Typing the Path" section later in this topic.
How to Create Simple Scripts
The following sections show you how to create a "Hello World" script by using Windows PowerShell and how to list only Virtual Machine Manager cmdlets (that is, without also listing the core Windows PowerShell cmdlets). After that, the "How to Convert an Existing Cmdlet Help Example to a Script" section shows you how to create a script from any of the hundreds of examples available in the Virtual Machine Manager command-line Help.
How to Create a Windows PowerShell 'Hello World' Script
The following procedure shows you how to configure Windows PowerShell to allow scripting, which you must do before you can create the 'Hello World' script or any other script.
To enable scripting on your server
1. On a Virtual Machine Manager server on which the Administrator Console for Virtual Machine Manager is installed, click Start, point to All Programs, point to Microsoft System Center Virtual Machine Manager 2007, and then click Windows PowerShell - Virtual Machine Manager to open the command shell. 2. Type the following command to determine the current execution policy on the computer: Get-ExecutionPolicy 3. Decide which execution policy you want to enable on the computer. This procedure assumes that: ï‚· You are using a test server in a protected environment. ï‚· Currently, the execution policy is Restricted. ï‚· It is safe to change the execution policy to Unrestricted.
If you are working on a computer in your production environment, you might need to chose a more restrictive execution policy than Unrestricted. Refer to the information about the AllSigned and RemoteSigned execution policies described earlier in this topic. 4. Type the following command: Set-ExecutionPolicy -ExecutionPolicy Unrestricted 5. Type the following command to clear the screen: Clear-Host |
The following procedure shows you how to create and run a simple 'Hello World' script.
To create the "Hello World" script
1. Type the following command to change to the directory where you want to save the script: Set-Location 'My Documents\MyScripts'
These examples assume that, when you open the Windows PowerShell window, the current location is <C:>\Documents and Settings\<YourAlias> and that you have created a folder called MyScripts under your My Documents folder. 2. Type the following command to create and name the script: notepad Hello.ps1 3. When a dialog box appears asking whether you want to create a new file, click Yes. 4. When an empty Notepad window opens, confirm that Hello.ps1 appears in the Title bar. 5. Type the following series of comments and commands to create the script: # Filename: Hello.ps1 Write-Host Write-Host 'Hello World!' Write-Host "Good-bye World! `n" # end of script When you use single quotes, the text appears exactly as you type it. When you use double quotes, Windows PowerShell can recognize and evaluate entities such as escape sequences or variables: ï‚· Example of an escape sequence (used in the example script): The backtick character (`) followed by "n" is used to create a new line. ï‚· Example of a variable (not used in this example script): An initial dollar sign followed by a name that you specify. A variable, such as $MyVM, is used to store an object; in this case, the object represents a virtual machine. 6. Save and close the Notepad file. 7. Run the script by typing the script name at the Windows PowerShell command prompt: .\Hello If the script does not work, verify that you are working in the same directory in which the script is stored and that you preceded the script name with a period and a backslash. Alternatively, in step 1, you can type the entire path to the script. 8. Review the output to verify that the script is displayed as expected. |
How to List Only Virtual Machine Manager Cmdlets
The following procedure shows you how to create a Windows PowerShell script that lists only the Virtual Machine Manager cmdlets without also listing the core Windows PowerShell cmdlets.
To create a script that lists only Virtual Machine Manager cmdlets
1. Type a command to change to the directory where you want to save the script. For example: Set-Location 'My Documents\MyScripts' 2. Type the following command to create and name the script: notepad GetVMMCommand.ps1 3. When a dialog box appears asking whether you want to create a new file, click Yes. 4. Type the following series of comments and commands to create the script: # Filename: GetVMMCommand.ps1 # GetVMMCommand.ps1 lists all Windows PowerShell cmdlets for # Virtual Machine Manager but omits standard Windows PowerShell # cmdlets. Get-Command -PSSnapin VirtualMachineManagerSnapin # end of script
For more information about Windows PowerShell snap-ins, see the "How a Snap-in Provides Virtual Machine Manager Cmdlets" section in "Appendix A: About Windows PowerShell for Virtual Machine Manager" and see the "Sample Scripts for Managing Snap-ins" topic. 5. Save and close the Notepad file. 6. Run the script by typing the script name at the Windows PowerShell command prompt: .\GetVMMCommand.ps1 7. Review the output to verify that the script displays the Virtual Machine Manager cmdlets. |
How to Convert an Existing Cmdlet Help Example to a Script
The cmdlet Help that is built into the Windows PowerShell command shell for Virtual Machine Manager includes hundreds of examples of Virtual Machine Manager interactive commands that you can type at the command line. Many of these examples contain multiple lines of code and can be saved as a script. If you are not familiar with the cmdlet Help examples for Virtual Machine Manager, see "Appendix B: VMM Command-Line Tutorial."
How to Convert an Example for Restart-Job into a Script
The following procedure shows you how to take an existing example in the Virtual Machine Manager cmdlet Help and make it into a script.
To convert an existing cmdlet Help example into a script
1. Type a command to change to the directory where you want to save the script. For example: Set-Location 'My Documents\MyScripts' 2. Type the following command to create and name a script—for this example, you convert an existing cmdlet example into a script that illustrates how to restart canceled Virtual Machine Manager jobs: notepad RestartCancelledJobs.ps1 3. When a dialog box appears asking if you want to create a new file, click Yes. 4. At the top of the Notepad file, type: # Filename: RestartCancelledJobs.ps1 5. Click Start, click All Programs, click Microsoft System Center Virtual Machine Manager 2007, and then click Windows PowerShell - Virtual Machine Manager to open the command shell. 6. At the command line, type the following command to display the cmdlet Help examples for the Restart-Job cmdlet: Get-Help Restart-Job -example 7. Read the explanatory text for "EXAMPLE 1: Restart all jobs that were canceled on any virtual machine." 8. Copy the code for example 1 into the Notepad file: a. Right-click inside the Windows PowerShell window, select Mark, highlight the code for example 3, and then press ENTER to copy the example into the buffer.
If right-clicking the Windows PowerShell window does not display the Mark option, click the icon in the upper left-hand corner of the Windows PowerShell - Virtual Machine Manager title bar, click Edit, and then click Mark. b. Click the Notepad file that you created in step 2 (named RestartCancelledJobs.ps1) to make it the active window, right-click the Notepad file, position the cursor under the filename comment (# Filename: RestartCancelledJobs.ps1), and then click Paste. c. Confirm that the content of the Notepad file appears as follows: # Filename: RestartCancelledJobs.ps1 PS C:\> Get-VMMServer -ComputerName "<VMMServer1>.<Contoso>.com" PS C:\> Get-Job | where { $_.ResultName -eq "VM01" -and $_.Status -eq "Cancelled" } | Restart-Job d. Remove any hard returns in the middle of a line and then delete the text that represents the prompt (PS C:\>, which indicates the start of each line of code), so that the content of the Notepad file now appears as follows: # Filename: RestartCancelledJobs.ps1 Get-VMMServer -ComputerName "<VMMServer1>.<Contoso>.com" Get-Job | where { $_.ResultName -eq "VM01" -and $_.Status -eq "Cancelled" } | Restart-Job 9. Substitute the names that you use in your environment for the example names that are used in the cmdlet Help. In this example: ï‚· Substitute YourVMMServerName.YourDomainName.com for <VMMServer1>.<Contoso>.com 10. Save and close the Notepad file. |
How to Use the Profile.ps1 Script to Run Your Scripts Without Typing the Path
If you want to be able to run your scripts without typing the script path each time, you can create a special Windows PowerShell script called Profile.ps1 that provides the path to the folder where you store your scripts. If Windows PowerShell scripting is enabled, the Profile.ps1 script runs whenever you open a new Windows PowerShell window.
To enable Windows PowerShell scripts to run without typing the path
1. In Windows Explorer, navigate to <C>:\Documents and Settings\<UserAlias>\My Documents\ folder, and then create two new folders: <C>:\Documents and Settings\<UserAlias>\My Documents\MyScripts <C>:\Documents and Settings\<UserAlias>\My Documents\Windows PowerShell
You can create MyScripts in any folder that you want and you can name MyScripts any name that you want. However, you must create the Windows PowerShell folder under your My Documents folder, and you must include a space between Windows and PowerShell in the folder name. 2. Type the following command to create and name a script: notepad Profile.ps1 3. When a dialog box appears asking whether you want to create a new file, click Yes. 4. When an empty Notepad window opens, confirm that Profile.ps1 appears in the Title bar. 5. Type the following comment and command to create the script: # Filename: Profile.ps1 $env:path = $env:path + ";<C>:\Documents and Settings\<UserAlias>\My Documents\MyScripts" # end of script 6. Save Profile.ps1 in the new Windows PowerShell folder: <C>:\Documents and Settings\<UserAlias>\My Documents\Profile.ps1. 7. Open a new Windows PowerShell - Virtual Machine Manager command shell window. 8. Type the name of the Hello.ps1 script that you created earlier in this topic, without the path, and confirm that the script runs. |
How to Provide User Credentials in a Script
To perform certain common actions in Virtual Machine Manager, such as adding new host servers on which to deploy virtual machines, you are required to provide user credentials. Credentials are the user name and password of an account that has permissions to perform the task you want to accomplish. You can provide credentials within a single script, or you can provide credentials globally so that the credential are available to all scripts that you run in the same session.
How to Store Credentials That a Specific Script Can Re-Use
When you type the following core Windows PowerShell cmdlet at the Windows PowerShell command prompt, Windows PowerShell prompts you to enter a user name and password:
Get-Credential
After you type a user name and password, Windows PowerShell stores these credentials in a Windows PowerShell credential object (PSCredential object).
If you want to avoid being prompted each time a script requires user credentials, you can use the following command to store the credentials securely in a variable that the script can then reuse:
$Credential = Get-Credential
In this case, you are prompted only once for the credentials. The following example, shows a script for adding hosts to Virtual Machine Manager and demonstrates how to use this command in a script.
Caution
It is possible to produce a PSCredential object programmatically through Windows PowerShell without requiring user interaction. However, this method requires that the user name and password appear in plain text in the script and is therefore not recommended.
How to Provide Credentials in a Script That Adds Hosts
The following procedure shows you how to create a Virtual Machine Manager script that lets you add a series of servers to Virtual Machine Manager as hosts for virtual machines. It also demonstrates how to store credentials for an account that has permissions to add hosts.
To create a script that adds a list of servers as hosts to Virtual Machine Manager
1. Before you run this script, make sure that the servers that you want to add as hosts meet the hardware and software requirements for Virtual Machine Manager described at http://go.microsoft.com/fwlink/?LinkId=69926. 2. Type a command to change to the directory where you want to save this script. For example: Set-Location 'My Documents\MyScripts' 3. Type the following command to create and name a script: notepad AddVMHostsList.ps1 4. When a dialog box appears asking if you want to create a new file, click Yes. 5. Type the following series of comments and commands to create the script:
Be sure to substitute your actual server names and domain name for <VMHost01>.<Contoso>.com, <VMHost02>.<Contoso>.com, and <VMMServer1>.<Contoso>.com. In addition, be sure to type each command on a single line even though the longer commands are shown here on multiple lines for readability. # Filename: AddVMHostsList.ps1 # Display a blank line. Write-Host # Send a message to the screen. Write-Host -backgroundColor Red "When the Windows PowerShell Credential Request dialog box opens, type a user name and password for an account with permission to add a host." # Store credentials with permissions to add hosts in a variable. $Credential = Get-Credential # Store host names in a variable. $ServerNames = "<VMHost01>.<Contoso>.com", "<VMHost02>.<Contoso>.com" # Add each server as a host. foreach( $ServerName in $ServerNames ) { Add-VMHost -VMMServer <VMMServer1>.<Contoso>.com -ComputerName $ServerName -Credential $Credential } # Display a blank line. Write-Host # end of script |
How to Store Credentials That All Scripts in a Session Can Re-Use
If you run multiple scripts that require credentials, you can use the following command to store the PSCredential object securely in a global variable that all scripts can make use of:
$global:Credential = Get-Credential
In this case, you can enter the required credentials one time when you start a session, and all scripts that run during that session will use the $Credential variable.
How WMI Enables Cross-Product Scripting
Virtual Machine Manager uses Windows Management Instrumentation (WMI) for cross-product scripting. WMI is the Microsoft implementation of Web-Based Enterprise Management (WBEM), an industry-wide standard technology for accessing information about components of Windows-based computers in an enterprise environment.
A WMI interface provides programmatic access to a system, enabling users to write command-line administration scripts and tools. This enables network administrators to collect and set configuration details on a wide variety of hardware, operating system components and subsystems, and application software.
WMI does not consolidate the management data in a central location; System Center Configuration Manager 2007 performs this function. Configuration Manager provides inventory collection, software deployment, and diagnostic tools; automates software upgrades; enables remote problem solving; provides asset management information; and monitors software usage, computers, and networks. This facilitates the management of multiple servers as a single system to increase availability and manageability of data and applications.
For more information about how to use WMI, see "Accessing WMI from Windows PowerShell" (http://go.microsoft.com/fwlink/?LinkId=98347).
For More Information
For Windows PowerShell topics that are available on the Microsoft Web site:
ï‚· Windows PowerShell in the Microsoft Developers' Network (MSDN) Library at http://go.microsoft.com/fwlink/?LinkId=86262
ï‚· Scripting with Windows PowerShell at http://go.microsoft.com/fwlink/?LinkId=71134
ï‚· Using the Exchange Management Shell at http://go.microsoft.com/fwlink/?LinkId=79421
For Virtual Machine Manager topics that are available on the Microsoft Web site:
ï‚· Microsoft TechCenter Web site for Virtual Machine Manager at http://go.microsoft.com/fwlink/?LinkId=85920
ï‚· Access to Virtual Machine Manager Community at http://go.microsoft.com/fwlink/?LinkId=85918
ï‚· Sign up for the Virtual Machine Manager newsgroup at http://go.microsoft.com/fwlink/?LinkId=85919
For conceptual Help topics that are available with the Virtual Machine Manager cmdlet Help, type Get-Help about_<TopicName> to display the following topics:
ï‚· about_VMM
ï‚· about_VMM_Tutorial
ï‚· about_VMM_Scripting
For conceptual Help topics that are available with the standard Windows PowerShell cmdlet Help, type Get-Command about_*_to list the topics (many of which provide scripting-related information) and then type Get-Help about_<TopicName> to display information about those topics that you want to read:
ï‚· about_Alias
ï‚· about_Array
ï‚· about_Assignment_Operators
ï‚· about_Associative_Array
ï‚· about_Automatic_Variables
ï‚· about_Break
ï‚· about_Command_Syntax
ï‚· about_Comparison_Operators
ï‚· about_Comparison_Operators
ï‚· about_Continue
ï‚· about_Core_commands
ï‚· about_Environment_Variable
ï‚· about_Escape_Character
ï‚· about_Execution_Environment
ï‚· about_Filter
ï‚· about_Flow_Control
ï‚· about_For
ï‚· about_Foreach
ï‚· about_Function
ï‚· about_If
ï‚· about_Location
ï‚· about_Logical_Operator
ï‚· about_Method
ï‚· about_Object
ï‚· about_Operator
ï‚· about_Parameter
ï‚· about_Path_Syntax
ï‚· about_Pipeline
ï‚· about_Property
ï‚· about_Provider
ï‚· about_PSSnapins
ï‚· about_Regular_Expression
ï‚· about_Scope
ï‚· about_Script_Block
ï‚· about_Shell_Variable
ï‚· about_Special_Characters
ï‚· about_Switch
ï‚· about_System_State
ï‚· about_Types
ï‚· about_Where
ï‚· about_While
ï‚· about_Wildcard
ï‚· Get-ExecutionPolicy
ï‚· Get-Member
ï‚· Get-WMIObject
ï‚· Set-ExecutionPolicy
Sample Scripts for Managing Snap-ins
You can experiment with the Windows PowerShell scripts that are described in this topic to learn how to automate adding one or more Windows PowerShell snap-ins to the command shell.
If you open the Windows PowerShell - Virtual Machine Manager command shell, you can run both standard Windows PowerShell cmdlets and Virtual Machine Manager cmdlets. However, if you open the standard Windows PowerShell command shell, the Virtual Machine Manager cmdlets are not available unless you add the Virtual Machine Manager snap-in to the standard shell.
In some cases, you can add multiple snap-ins to the standard Windows PowerShell command shell if you want to be able to view and use cmdlets for two or more Microsoft products in the same shell. In other cases, adding multiple snap-ins to the standard Windows PowerShell command shell will not work. For example, if you want to access Virtual Machine Manager cmdlets in the same command shell as System Center Operations Manager, the best way to accomplish it is to add the path for the Windows PowerShell console file for Virtual Machine Manager to the Windows PowerShell console file for System Center Operations Manager.
AddVMMSnapin.ps1
You can use the following script to automate adding the Virtual Machine Manager snap-in to the standard Windows PowerShell command shell. Copy the following complete version of AddVMMSnapin.ps1 into a Notepad file and save it as AddVMMSnapin.ps1.
# Filename: AddVMMSnapin.ps1
# Description: Adds the Virtual Machine Manager snap-in to the
# standard Windows PowerShell command shell.
# For this script to run successfully, Virtual Machine
# Manager must be installed on the server on which you
# run this script.
#
# 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.
#
######################################################################
# Add the VMM snap-in to the standard Windows PowerShell command shell.
######################################################################
#
Add-PSSnapin -name VirtualMachineManagerSnapIn
AddVMMExchSnapins.ps1
If you also want to run Windows PowerShell cmdlets for other Microsoft products, such as Microsoft Exchange Server, in the same command shell as the Virtual Machine Manager cmdlets, you must add the snap-ins for Virtual Machine Manager and the other products to the generic Windows PowerShell command shell.
Before You Start
You cannot add a snap-in that contains Windows PowerShell cmdlets for a particular Microsoft product to a server unless that product is installed on that server and a Windows PowerShell snap-in exists for that product.
To determine which Windows PowerShell snap-ins you can add on a server
1. On a server on which Virtual Machine Manager and Microsoft Exchange Server are installed, click Start, point to All Programs, point to Windows PowerShell 1.0, and then click Windows PowerShell.
Do not click Start, point to All Programs, point to Microsoft System Center Virtual Machine Manager 2007, and then click Windows PowerShell - Virtual Machine Manager. You cannot add snap-ins for other Microsoft products to the Windows PowerShell - Virtual Machine Manager command shell. 2. To determine which snap-ins you can add to the standard Windows PowerShell console, type the following command at the command prompt: Get-PSSnapin -Registered This example assumes that Virtual Machine Manager and Microsoft Exchange Server are installed on the server, so the output should list a Windows PowerShell snap-in for each of these server products. |
Add-VMMExchSnapins.ps1 - Complete Script
You can use the following script to automate adding the Virtual Machine Manager and Microsoft Exchange Server snap-ins to the standard Windows PowerShell command shell. Copy the following complete version of AddVMMExchSnapins.ps1 into a Notepad file and save it as AddVMMExchSnapins.ps1.
# Filename: AddVMMExchSnapins.ps1
# Description: Adds two snap-ins to the standard Windows PowerShell
# command shell: Virtual Machine Manager, and Microsoft
# Exchange Server. For this script to run
# successfully, both server products must be installed
# on the server on which you run this script.
#
# 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.
#
######################################################################
# Add the VMM and Exchange snap-ins to the standard Windows
# PowerShell command shell.
######################################################################
#
Add-PSSnapIn -Name VirtualMachineManagerSnapIn, Microsoft.Exchange.Management.PowerShell.Admin
AddVMMCmdletsToOpsMgrConsole.ps1
If you want to make both Virtual Machine Manager cmdlets and System Center Operations Manager cmdlets available in the same Windows PowerShell window, you cannot use the Windows PowerShell cmdlet Add-PSSnapIn as described in the preceding section. If you did so, you would lose Operations Manager functionality for two reasons:
ï‚· The Operations Manager implementation of Windows PowerShell includes a provider in addition to cmdlets, but the Virtual Machine Manager implementation of Windows PowerShell includes only cmdlets.
ï‚· When you open Windows PowerShell from Operations Manager, Operations Manager loads its own Windows PowerShell console, and it also loads its own custom startup script.
You can use the following procedure to confirm that Operations Manager runs a custom startup script when you open the Operations Manager version of the command shell.
To confirm that Operations Manager runs a custom startup script when you open its console
1. On a server on which Operations Manager is installed, click Start, point to All Programs, point to System Center Operations Manager 2007, right-click Command Shell, and then click Properties. 2. View the contents of the Target field: <C>:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -PSConsoleFile Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Console.psc1 -NoExit .\Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Startup.ps1 Notice that, after loading the Windows PowerShell console for Operations Manager, the command in the Target field also runs the custom script called Startup.ps1. |
You can accommodate the Operations Manager provider and its startup script and you can also make Virtual Machine Manager cmdlets available by adding the Virtual Machine Manager cmdlets to the Operations Manager console. You can use the following procedure to make Machine Manager cmdlets available in the Operations Manager command shell.
To add Virtual Machine Manager cmdlets to the Operations Manager console
1. On a computer on which both Virtual Machine Manager and Operations Manager are installed, open Windows Explorer and navigate to: C:\Program Files\System Center Operations Manager 2007 2. Open Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Console.psc1 in Notepad. 3. Confirm that the original contents of the .psc1 console script file appear as follows: <?xml version="1.0" encoding="utf-8"?> <PSConsoleFile ConsoleSchemaVersion="1.0"> <PSVersion>1.0</PSVersion> <PSSnapIns> <PSSnapIn Name="Microsoft.EnterpriseManagement.OperationsManager.Client" /> </PSSnapIns> </PSConsoleFile> 4. Add <PSSnapIn Name="VirtualMachineManagerSnapIn" />, which loads the Virtual Machine Manager cmdlets, to Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Console.psc1 to , so that the Operations Manager . psc1 console script file appears as follows: <?xml version="1.0" encoding="utf-8"?> <PSConsoleFile ConsoleSchemaVersion="1.0"> <PSVersion>1.0</PSVersion> <PSSnapIns> <PSSnapIn Name="Microsoft.EnterpriseManagement.OperationsManager.Client" /> <PSSnapIn Name="VirtualMachineManagerSnapIn" /> </PSSnapIns> </PSConsoleFile> 5. Save and close Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Console.psc1. |
Sample Script for Upgrading Hosts and Library Servers
You can experiment with the Windows PowerShell script that is described in this topic to learn how to automate updating the agent software on hosts and library servers that are managed by Virtual Machine Manager.
UpgradeAgents.ps1
After you upgrade your Virtual Machine Manager server to a later version of the Virtual Machine Manager service, update the Virtual Machine Manager agent software that is installed on computers that are managed by that Virtual Machine Manager server to the current version of the agent software. You can use the UpgradeAgents.ps1 script to automate that update.
Managed computers on which you might need to update the agent software include:
ï‚· Host servers on which you deploy virtual machines.
ï‚· Library servers on which you store library resources.
How UpgradeAgents.ps1 Works
The UpgradeAgents.ps1 script performs the following tasks:
ï‚· Connects to the Virtual Machine Manager server and retrieves the object that represents the server from the Virtual Machine Manager database. Connecting to the Virtual Machine Manager server retrieves the server object from the Virtual Machine Manager database and gives you access to all other objects in the SQL Server database that stores all Virtual Machine Manager objects for as long as the connection lasts or until you close the command-shell window.
ï‚· Uses the Virtual Machine Manager cmdlet, Get-VMMManagedComputer, to get the objects that represent all computers managed by Virtual Machine Manager (that is, to retrieve from the Virtual Machine Manager database the objects for all virtual machine hosts and all library servers); uses the standard Windows PowerShell cmdlet, Where-Object, (whose alias is "where") to select from the set of all managed computers only objects for those managed computers whose agent software is not current; and stores the selected computer objects in variable $VMMManagedComputers.
ï‚· Uses the standard Windows PowerShell cmdlet, Get-Credential, to prompt you to provide credentials that have permissions to update computers that are managed by Virtual Machine Manager.
ï‚· Uses a ForLoop to perform the following tasks:
ï‚· Loops through each object in $VMMManagedComputer in turn.
ï‚· Uses the Virtual Machine Manager cmdlet, Update-VMMManagedComputer, to install updated agent software on each managed computer, by using the credentials you provided earlier for each update.
UpgradeAgents.ps1 - Complete Script
Copy the following complete version of UpgradeAgents.ps1 into a Notepad file and save it as UpgradeAgents.ps1:
# Filename: UpgradeAgents.ps1.ps1
# Description: Updates the System Center Virtual Machine Manager
# agent software on any managed computer (that is, any
# host or library server) that is running an earlier
# version of the agent software.
# 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:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
####################################################################
# Get the object that represents each managed computer which is
# not running the current version of the VMM agent software.
####################################################################
$VMMManagedComputers = Get-VMMManagedComputer | where {$_.VersionStateString -NE "Current"}
####################################################################
# When prompted, type the user name and password of an account
# with permissions to update both hosts and library servers.
####################################################################
$Creds = Get-Credential
####################################################################
# Loop through each managed computer that is not up-to-date
# and update its VMM agent software.
####################################################################
ForEach ($Computer in $VMMManagedComputers )
{
# Upgrade the agents On the managed computers
Update-VMMManagedComputer -Credential $Creds
}
Sample Script for Managing Hosts
You can experiment with the Windows PowerShell script in this topic to learn how to script adding to Virtual Machine Manager computers that are running Virtual Server but that are not currently managed by Virtual Machine Manager.
AddVSServerAsHost.ps1
You can use the AddVSServerAsHost.ps1 script to search Active Directory for servers that have Virtual Server 2005 R2 installed but are not currently managed by Virtual Machine Manager. You can use the script to add those servers as managed virtual machine hosts.
How AddVSServerAsHost.ps1 Works
The following sections explain each part of the script AddVSServerAsHost.ps1.
Connect to VMM Server
The first command in the script AddVSServerAsHost.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
####################################################################
# Substitute the name of your VMM server and domain in this command:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
Define a Function That Returns the FQDN of a Computer
The next set of commands in the script AddVSServerAsHost.ps1 defines a function in which Windows PowerShell uses C# commands to return the fully qualified domain name (FQDN) of a computer by performing the following tasks:
ï‚· Retrieves the domain name and computer name of a computer from the Lightweight Directory Access Protocol (LDAP) string for that computer.
ï‚· Concatenates the domain name and computer name to return the computer's FQDN.
The script invokes the defined function later (in the ForEach loop) after first using an LDAP (Lightweight Directory Access Protocol) query to return from Active Directory objects that represent all computers on which Virtual Server 2005 R2 is installed.
LDAP, an industry standard that is implemented by both Windows operating systems and non-Windows operating systems, is the primary directory access protocol that Windows operating systems use to add, modify, and delete information that is stored in Active Directory and to query and retrieve data from Active Directory. For more information about LDAP, see "Lightweight Directory Access Protocol" at http://go.microsoft.com/fwlink/?LinkId=104719.
####################################################################
# Define a function that selects the FQDN of a computer from the
# LDAP string returned from Active Directory by the LDAP query.
# (The LDAP query occurs later in this script.)
####################################################################
function Get-FQDN
{
# Declare the parameter for the LDAP string.
Param( $LDAPString )
# Get the domain name from the LDAP string.
$Domain = $LDAPString.ToString().SubString( $LDAPString.ToString().IndexOf(",DC=") + 4 )
$Domain = $Domain.ToString().Replace(",DC=", ".")
# Get the computer name from the LDAP string.
$ComputerName = $LDAPString.Split(',')[1].Remove(0,3)
# Return the FQDN from the function.
Return $ComputerName + "." + $Domain
}
Define a Function That Adds a Computer to VMM as a Host
The next set of commands in the script AddVSServerAsHost.ps1 defines a function that adds a computer as a managed host to Virtual Machine Manager by performing the following tasks:
ï‚· Displays a message each time a host is added.
ï‚· Retrieves the object that represents the group to which the host will be added, and adds the host to that group.
ï‚· Enables Virtual Machine Remote Control (VMRC) and configures several VMRC settings: The script allows only one connection at a time to a virtual machine by disabling multiple VMRC connections; sets the VMRC port to 5900 (the default port); enables a VMRC timeout interval (the length of time a VMRC connection remains idle before it is automatically disconnected); and sets the VMRC timeout interval to 30 minutes.
Note
VMRC 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 enables users to access their virtual machines remotely.
The script will invoke the defined function later (in the ForEach loop), after it uses the Get-FQDN function to retrieve the FQDN of computers that are running Virtual Server and after it selects only those computers that are running Virtual Server and that are not already managed by Virtual Machine Manager.
####################################################################
# Define a function that adds a computer as a host to VMM
####################################################################
function Add-NewVMHost
{
# Declare the parameter for the name of the host.
param( $HostName )
# Display a message each time a host is added.
"Adding host '" + $HostName + "'..."
# Get the object that represents the host group in which you want
# to place a new host.
$HostGroup = Get-HostGroup -Name "All Hosts"
# Add the new host to the specified host group and configure VMRC.
Add-VMHost -ComputerName $HostName -VMHostGroup $HostGroup -VMRCEnabled $TRUE -VMRCMultipleConnectionsEnabled $FALSE -VMRCPort 5900 -VMRCTimeoutEnabled $TRUE -VMRCTimeoutMinutes 30
}
Identify Servers Running Virtual Server 2005 R2
The next set of commands in the script AddVSServerAsHost.ps1 uses an LDAP query to identify servers that are running Virtual Server 2005 R2 by performing the following tasks:
ï‚· Creates an object that represents the organizational unit (OU) container for all computers that are located in the Contoso.com domain, and stores the object in variable $Root. The name $Root is used to indicate that the root of the search to be performed is set at the OU in the directory hierarchy.
ï‚· Creates a directory search object that is used to search $Root for objects that represent computers on which the Virtual Server service is installed, and then stores the search object in $Searcher.
ï‚· Runs an LDAP query to find the object that represents each computer on which Virtual Server is installed and stores the returned objects as an object array in variable $Result.
The script loops through each object in $Result later (in the ForEach loop) to determine whether a given object is or is not already managed by Virtual Machine Manager.
####################################################################
# Use an LDAP query to get computers running Virtual Server 2005 R2.
####################################################################
# Create an object that represents the OU container for computers in
# the Contoso.com domain, and store the new object in variable $Root.
$Root = New-Object DirectoryServices.DirectoryEntry "LDAP://OU=Computers,DC=contoso,DC=com"
# Create a directory search object to search $Root for objects that
# represent computers on which Virtual Server is installed, and store
# the search object in variable $Searcher.
$Searcher = New-Object DirectoryServices.DirectorySearcher $Root, "(&(objectCategory=serviceConnectionPoint)(CN=MS Virtual Server))"
# Run the LDAP query and store the returned objects as an
# object array in variable $Result.
$Result = $Searcher.FindAll()
Add Non-VMM Computers Running Virtual Server to VMM
The last set of commands in the script AddVSServerAsHost.ps1 adds each computer to Virtual Machine Manager if it is running Virtual Server 2005 R2 but is not currently managed by Virtual Machine Manager by using a ForEach loop to perform the following tasks:
ï‚· Loops through each object in $Result (that is, each server running Virtual Server) in turn.
ï‚· Uses the Get-FQDN function that was defined earlier to get the FQDN of each computer in $Result.
ï‚· Uses the Virtual Machine Manager cmdlet Get-VMHost to determine whether a computer in $Result is already managed by Virtual Machine Manager.
ï‚· If a computer in $Result is not currently managed by Virtual Machine Manager, the script uses the Add-NewVMHost function that was defined earlier to add the computer to Virtual Machine Manager.
####################################################################
# Process each object in $Result (that is, each computer running
# Virtual Server) and add that computer to the VMM database if it
# has Virtual Server installed but is not yet a VMM host.
####################################################################
ForEach ($Object in $Result)
{
# Get the fully qualified domain name.
$FQDN = Get-FQDN( $Object.GetDirectoryEntry().DistinguishedName.ToString() )
# Determine whether the computer is already managed by VMM and,
# if not, add it to VMM as a managed host.
If(!(Get-VMHost | where {$_.Name -Eq $FQDN}))
{
# Else (if the computer is not a host), add it to VMM as a host
Add-NewVMHost $FQDN
}
}
AddVSServerAsHost.ps1 - Complete Script
Copy the following complete version of AddVSServerAsHost.ps1 into a Notepad file, and save it as AddVSServerAsHost.ps1.
# Filename: AddVSServerAsHost.ps1
# Description: Search Active Directory for servers on which
# Virtual Server 2005 R2 is installed that are
# not currently managed by System Center Virtual
# Machine Manager. Add those servers as hosts to
# Virtual Machine Manager.
# 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.
####################################################################
# 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 a function that selects the FQDN of a computer from the
# LDAP string returned from Active Directory by the LDAP query.
# (The LDAP query occurs later in this script.)
####################################################################
function Get-FQDN
{
# Declare the parameter for the LDAP string.
Param( $LDAPString )
# Get the domain name from the LDAP string.
$Domain = $LDAPString.ToString().SubString( $LDAPString.ToString().IndexOf(",DC=") + 4 )
$Domain = $Domain.ToString().Replace(",DC=", ".")
# Get the computer name from the LDAP string.
$ComputerName = $LDAPString.Split(',')[1].Remove(0,3)
# Return the FQDN from the function.
Return $ComputerName + "." + $Domain
}
####################################################################
# Define a function that addS a computer as a host to VMM
####################################################################
function Add-NewVMHost
{
# Declare the parameter for the name of the host.
param( $HostName )
# Display a message each time a host is added.
"Adding host '" + $HostName + "'..."
# Get the object that represents the host group in which you want
# to place a new host.
$HostGroup = Get-HostGroup -Name "All Hosts"
# Add the new host to the specified host group and configure VMRC.
Add-VMHost -ComputerName $HostName -VMHostGroup $HostGroup -VMRCEnabled $TRUE -VMRCMultipleConnectionsEnabled $FALSE -VMRCPort 5900 -VMRCTimeoutEnabled $TRUE -VMRCTimeoutMinutes 30
}
####################################################################
# Use an LDAP query to get computers running Virtual Server 2005 R2.
####################################################################
# Create an object that represents the OU container for computers in
# the Contoso.com domain and store the new object in variable $Root.
$Root = New-Object DirectoryServices.DirectoryEntry "LDAP://OU=Computers,DC=contoso,DC=com"
# Create a directory search object to search $Root for objects that
# represent computers on which Virtual Server is installed, and store
# the search object in variable $Searcher.
$Searcher = New-Object DirectoryServices.DirectorySearcher $Root, "(&(objectCategory=serviceConnectionPoint)(CN=MS Virtual Server))"
# Run the LDAP query and then store the returned objects as an
# object array in variable $Result.
$Result = $Searcher.FindAll()
####################################################################
# Process each object in $Result (that is, each computer running
# Virtual Server) and add that computer to the VMM database if it
# has Virtual Server installed but is not yet a VMM host.
####################################################################
ForEach ($Object in $Result)
{
# Get the fully qualified domain name.
$FQDN = Get-FQDN( $Object.GetDirectoryEntry().DistinguishedName.ToString() )
# Determine whether the computer is already managed by VMM and,
# if not, add it to VMM as a managed host.
If(!(Get-VMHost | where {$_.Name -Eq $FQDN}))
{
# Else (if the computer is not a host), add it to VMM as a host
Add-NewVMHost $FQDN
}
}
QuickMigrate-VM.ps1
The QuickMigrate-VM.psi script quickly migrates a highly available virtual machine from its existing host to the best rated host that is part of the same host cluster.
The virtual machine must be configured as a highly available virtual machine (using Havm.vbs script) on Windows Server 2003 host cluster. The virtual machine must have its Custom7 property set to the name of the cluster resource group that it belongs to.
All the nodes of the Windows Server 2003 host cluster must be added as hosts in the Virtual Machine Manager 2007. All the clustered hosts must have their Custom7 property set to the name of the host cluster to which they belong.
QuickMigrate-VM.ps1 - Complete Script
# 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.
##################################################################################
# Check usage
##################################################################################
param ($VMName, $VMMServerName)
if ($VMName -eq $null -or $VMMServerName -eq $null)
{
Write-Host -foregroundcolor DarkGray "`nUsage: QuickMigrate-VM -VMName <String> -VMMServerName <String>"
Write-Host -foregroundcolor DarkGray "`nQuickly migrates a highly available virtual machine from its existing"
Write-Host -foregroundcolor DarkGray "host to the best rated host that is part of the same host cluster."
Write-Host -foregroundcolor DarkGray "`nThe virtual machine must be configured as a highly available virtual"
Write-Host -foregroundcolor DarkGray "machine (using havm.vbs script) on Windows Server 2003 host cluster."
Write-Host -foregroundcolor DarkGray "The virtual machine must have its Custom7 property set to the name"
Write-Host -foregroundcolor DarkGray "of the cluster resoruce group that it belongs to."
Write-Host -foregroundcolor DarkGray "`nAll the nodes of the Windows Server 2003 host cluster must be added"
Write-Host -foregroundcolor DarkGray "as hosts in the Virtual Machine Manager 2007. All the clustered hosts"
Write-Host -foregroundcolor DarkGray "must have its Custom7 property set to the name of the host cluster"
Write-Host -foregroundcolor DarkGray "that they belong to."
Write-Host -foregroundcolor DarkGray "`nUser running the script must be VMM administrator as well as cluster"
Write-Host -foregroundcolor DarkGray "administrator."
Write-Host
return
}
##################################################################################
# Connect to Virtual Machine Manager server
##################################################################################
Write-Host "`nTrying to connect to Virtual Machine Manager server $VMMServerName. This may take some time..."
$VMMServer = Get-VMMServer -ComputerName $VMMServerName
if ($VMMServer -eq $null)
{
Write-Host " ERROR: Cannot connect to Virtual Machine Manager server $VMMServerName`n" -foregroundcolor Red
return
}
else
{
Write-Host " Done!`n" -foregroundcolor Yellow
}
##################################################################################
# Get cluster resource group name which is Custom7 property of virtual machine
##################################################################################
Write-Host "Trying to find virtual machine $VMName..."
$VM = Get-VM -Name $VMName
if ($VM -eq $null)
{
Write-Host " ERROR: Cannot find virtual machine $VMName in VMM server $VMMServerName`n" -foregroundcolor Red
return
}
else
{
Write-Host " Done!`n" -foregroundcolor Yellow
}
Write-Host "Trying to get cluster resource group name by reading Custom7 property of virtual machine $VMName..."
if ($VM.CustomProperties[6] -eq "")
{
Write-Host " ERROR: $VMName does not appear to be highly available virtual machine since its Custom7 property is blank`n" -foregroundcolor Red
return
}
else
{
$ResourceGroupName = $VM.CustomProperties[6]
Write-Host " Done! Cluster resource group name is '$ResourceGroupName'`n" -foregroundcolor Yellow
}
##################################################################################
# Get host cluster name which is Custom7 property of virtual machine host
##################################################################################
Write-Host "Trying to find current host of virtual machine $VMName..."
$VMHostName = ($VM.HostName).split(".")[0]
$VMHost = Get-VMHost -ComputerName $VMHostName
if ($VMHost -eq $null)
{
Write-Host " ERROR: Cannot find virtual machine host $VMHostName in VMM server $VMMServerName`n" -foregroundcolor Red
return
}
else
{
Write-Host " Done! Current host is $VMHostName`n" -foregroundcolor Yellow
}
Write-Host "Trying to get host cluster name by reading Custom7 property of host $VMHostName..."
if ($VMHost.Custom7 -eq "")
{
Write-Host " ERROR: $VMHostName does not appear to be a clustered host since its Custom7 property is blank`n" -foregroundcolor Red
return
}
else
{
$ClusterName = $VMHost.Custom7
Write-Host " Done! Host cluster name is $ClusterName `n" -foregroundcolor Yellow
}
##################################################################################
# Ensure that the host cluster exists
##################################################################################
Write-Host "Trying to connect to host cluster $ClusterName. This may take some time..."
$Cluster = Get-WmiObject -class MSCluster_Cluster -namespace root\mscluster -computerName $ClusterName
if ($Cluster -eq $null)
{
Write-Host " ERROR: Cannot connect to host cluster $ClusterName `n" -foregroundcolor Red
return
}
else
{
Write-Host " Done!`n" -foregroundcolor Yellow
}
##################################################################################
# Ensure that the current host is part of the host cluster
##################################################################################
Write-Host "Trying to find current host $VMHostName in host cluster $ClusterName..."
$Node = Get-WmiObject -class MSCluster_Node -namespace root\mscluster -computerName $ClusterName -filter "Name='$VMHostName'"
if ($Node -eq $null)
{
Write-Host " ERROR: Cannot find current host $VMHostName in host cluster $ClusterName`n" -foregroundcolor Red
return
}
else
{
Write-Host " Done!`n" -foregroundcolor Yellow
}
##################################################################################
# Ensure that the cluster resource group is owned by the current host
##################################################################################
Write-Host "Trying to find cluster resource group $ResourceGroupName on current host $VMHostName..."
$Query = "select * from MSCluster_NodeToActiveGroup where GroupComponent=`"MSCluster_Node.Name='$VMHostName'`" and PartComponent=`"MSCluster_ResourceGroup.Name='$ResourceGroupName'`""
$NodeToActiveGroup = Get-WmiObject -namespace root\mscluster -computerName $ClusterName -query $Query
if ($NodeToActiveGroup -eq $null)
{
Write-Host " ERROR: Cannot find cluster resource group $ResourceGroupName on current host $VMHostName`n" -foregroundcolor Red
return
}
else
{
$ResourceGroup = Get-WmiObject -class MSCluster_ResourceGroup -namespace root\mscluster -computerName $ClusterName -filter "Name='$ResourceGroupName'"
Write-Host " Done!`n" -foregroundcolor Yellow
}
##################################################################################
# Get the best rated target host
##################################################################################
Write-Host "Trying to select the best rated host having Custom7 set to $ClusterName as target for quick migration..."
$TargetVMHosts = @(Get-VMHost) | where {($_.Custom7 -eq $ClusterName) -and ($_.Name -ne $VMHost.Name)}
if ($TargetVMHosts -eq $null)
{
Write-Host " ERROR: Cannot find any target hosts having Custom7 set to $ClusterName`n" -foregroundcolor Red
return
}
else
{
$TargetVMHostRatings = @(Get-VMHostRating -VM $VM -VMHost $TargetVMHosts) | Sort-Object -property Rating -descending
Write-Host
Write-Host " TARGET HOST`t`tVMM RATING" -foregroundcolor DarkGray
Write-Host " ===========`t`t==========" -foregroundcolor DarkGray
foreach ($TargetVMHostRating in $TargetVMHostRatings)
{
Write-Host " ", ($TargetVMHostRating.Name).split(".")[0], "`t`t", $TargetVMHostRating.Rating -foregroundcolor DarkGray
}
Write-Host
$TargetHostName = (@($TargetVMHostRatings)[0].Name).split(".")[0]
Write-Host " Done! Selected target host $TargetHostName`n" -foregroundcolor Yellow
}
##################################################################################
# Ensure that the target host is part of the host cluster
##################################################################################
Write-Host "Trying to find target host $TargetHostName in host cluster $ClusterName..."
$Node = Get-WmiObject -class MSCluster_Node -namespace root\mscluster -computerName $ClusterName -filter "Name='$TargetHostName'"
if ($Node -eq $null)
{
Write-Host " ERROR: Cannot find target host $TargetHostName in host cluster $ClusterName`n" -foregroundcolor Red
return
}
else
{
Write-Host " Done!`n" -foregroundcolor Yellow
}
##################################################################################
# Move the cluster resource group to the target host
##################################################################################
Write-Host "Quick-migrating virtual machine $VMName to the best rated host $TargetHostName. This may take some time. "
$ResourceGroup.MoveToNewNode($TargetHostName, 30)
Write-Host " Done!`n" -foregroundcolor Yellow
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 ”.
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”
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;
}
Sample Scripts for Managing Self-Service Policies
You can experiment with the Windows PowerShell scripts in this topic to learn how to use scripts to create Virtual Machine Manager self-service policies. These policies govern the actions that users, who are not Virtual Machine Manager server administrators are allowed to take if you grant them permission to access and, optionally, create and manage their own virtual machines.
What actions a self-service user, or members of a self-service group, can take depend on which permissions you grant to the Active Directory user account or group to whom you grant self-service permissions. The mechanism you use to grant these permissions is the self-service policy. You configure self-service policies for a host group and enable an Active Directory user or group to have self-service access to virtual machines that are deployed on hosts in a given host group. A host group contains a set of physical computers, managed by Virtual Machine Manager, that host virtual machines.
The scripts in this topic are similar to each other in structure but differ depending on the level of permissions granted to self-service users. The example script names are lengthy to indicate what each script does. You might prefer to use shorter names for your scripts.
Before You Start
Before you can create functioning self-service policies, you must understand how Virtual Machine Manager self-service policies work. In addition, because self-service users access their virtual machines through a Web site called the Self-Service Portal that you configure in Virtual Machine Manager, you must set up the Web site that acts as the Self-Service Portal before granting users self-service rights.
For information about self-service policies and the Self-Service Portal, type the following commands at the Windows PowerShell - Virtual Machine Manager command and then read the "Detailed Description" section for each cmdlet:
Get-Help New-SelfServicePolicy -detailed
Get-Help Add-SelfServiceWebServer -detailed
You can also read the self-service topics in the online Help available in the Administrator Console.
CreateSelfServicePolicy_AccessVMs.ps1
You can use the CreateSelfServicePolicy_AccessVMs.ps1 script to create a self-service policy that grants members of an Active Directory group permissions to access and use their virtual machines through the Self-Service Portal.
How CreateSelfServicePolicy_AccessVMs.ps1 Works
The following sections explain each part of the script CreateSelfServicePolicy_AccessVMs.ps1.
Connect to the Virtual Machine Manager Server
The first command in the script 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.
####################################################################
# Substitute the name of your VMM server and domain in this command:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
Define Variables for CreateSelfServicePolicy_AccessVMs.ps1
The second set of commands in the script performs the following tasks:
ï‚· Identifies the Virtual Machine Manager host group, HGroup1, as the host group for the self-service policy and store the host group object in variable $VMHostGroup1.
ï‚· Identifies the Active Directory user account or security group to which the self-service policy applies and stores its object in variable $ADUserOrGroup1. The following example uses the Active Directory group, SelfServGroup1, located in the Contoso.com domain.
ï‚· Names the self-service policy and stores the name in variable $Policy1.
ï‚· Specifies a set of self-service policy permissions and stores the permissions object in variable $ReadOnlyPermissions. The following example grants only the permission Vmrc, which refers to Virtual Machine Remote Control (VMRC). VMRC is a feature of Microsoft Virtual Server that lets a VMRC client connect to an instance of Virtual Server (a host server) to access that host's virtual machines. VMRC lets users access their virtual machines remotely.
Note
ï‚· To see a list of all possible self-service permissions, type the following command on a single line:
ï‚· [enum]::GetValues([Microsoft.VirtualManager.Remoting.SelfServicePermission])
####################################################################
# Define variables for CreateSelfServicePolicy_AccessVMs.ps1
####################################################################
$VMHostGroup1 = Get-VMHostGroup | where { $_.Name -eq "HGroup1" }
$ADUserOrGroup1 = "Contoso\SelfServGroup1"
$Policy1 = "SelfServGroup1 on HGroup1"
$ReadOnlyPermissions = 'Vmrc'
Create a Self-Service Policy for SelfServGroup1
The third command in the script performs the following tasks:
ï‚· Creates and names a self-service policy.
ï‚· Specifies that members of the Active Directory group whose object is stored in $ADUserOrGroup1 (SelfServGroup1) are governed by the policy.
ï‚· Specifies that the policy applies to virtual machines that are deployed on hosts that belong to the host group (HGroup1) whose object is stored in $VMHostGroup1.
ï‚· Grants users governed by the policy Read Only permissions (only the Vmrc permission is granted).
ï‚· Specifies that all users of the policy share the ownership of the virtual machines governed by the policy.
ï‚· Stores the object that represents the new self-service policy in variable $SSPol_ReadOnly.
####################################################################
# Create a self-service policy for this set of users.
####################################################################
$SSPol_ReadOnly = New-SelfServicePolicy -Name $Policy1 -UserOrGroup $ADUserOrGroup1 -VMHostGroup $VMHostGroup1 -VMPermission $ReadOnlyPermissions -SharedVMOwnership $True
Make Virtual Machines Available to Members of SelfServGroup1
The last set of commands in the script performs the following tasks:
ï‚· Gets the objects that represent the set of virtual machines whose name begins with the prefix "SSVM10" and stores the virtual machine objects in variable array $UserVMsSet1.
ï‚· Uses the pipeline operator (|) to pass the objects in $UserVMsSet1 to the Set-VM cmdlet, which sets the members of $ADUserOrGroup1 as owners of the policy $SSPol_ReadOnly so that the virtual machines that are available to the group are displayed to its members.
Note
The following example assumes that the set of virtual machines that you want to assign to the group uses the naming convention SSVM100, SSVM102, SSVM103, and so on up to 109.
####################################################################
# Find VMs for this group and set the ownership and policy so that
# the VMs available to this group will display to group members.
####################################################################
$UserVMsSet1 = Get-VM -Name "SSVM10*"
$UserVMsSet1 | Set-VM -Owner $ADUserOrGroup1 -SelfServicePolicy $SSPol_ReadOnly
CreateSelfServicePolicy_AccessVMs.ps1 - Complete Script
Copy the following complete version of CreateSelfServicePolicy_AccessVMs.ps1 into a Notepad file and save it as CreateSelfServicePolicy_AccessVMs.ps1:
# Filename: CreateSelfServicePolicy_AccessVMs.ps1.
# Description: Create a self-service policy that grants System Center
# Virtual Machine Manager self-service users permissions
# to access and use their VMs, and set their VMs to be
# covered by that policy.
# 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:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
####################################################################
# Define variables for CreateSelfServicePolicy_AccessVMs.ps1.
####################################################################
$VMHostGroup1 = Get-VMHostGroup | where { $_.Name -eq "HGroup1" }
$ADUserOrGroup1 = "Contoso\SelfServGroup1"
$Policy1 = "SelfServGroup1 on HGroup1"
$ReadOnlyPermissions = 'Vmrc'
# To see a list of all possible self-service permissions, type:
# [enum]::GetValues([Microsoft.VirtualManager.Remoting.
# SelfServicePermission])
####################################################################
# Create a self-service policy for this set of users.
####################################################################
$SSPol_ReadOnly = New-SelfServicePolicy -Name $Policy1 -UserOrGroup $ADUserOrGroup1 -VMHostGroup $VMHostGroup1 -VMPermission $ReadOnlyPermissions -SharedVMOwnership $True
####################################################################
# Find VMs for this group and set the ownership and policy so that
# the VMs available to this group will display to group members.
####################################################################
$UserVMsSet1 = Get-VM -Name "SSVM10*"
$UserVMsSet1 | Set-VM -Owner $ADUserOrGroup1 -SelfServicePolicy $SSPol_ReadOnly
CreateSelfServicePolicy_ManageVMs.ps1
You can use the CreateSelfServicePolicy_ManageVMs.ps1 script to create a self-service policy that grants members of an Active Directory group permissions not only to access their virtual machines but also to have certain management privileges. These include permission to start, stop, pause and resume, and shut down their virtual machines and permission to create checkpoints for their virtual machines.
How CreateSelfServicePolicy_ManageVMs.ps1 Works
The following sections explain each part of the script CreateSelfServicePolicy_ManageVMs.ps1.
Connect to the Virtual Machine Manager Server
The first command in the script 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.
####################################################################
# Substitute the name of your VMM server and domain in this command:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
Define Variables for CreateSelfServicePolicy_ ManageVMs.ps1
The second set of commands in the script performs the following tasks:
ï‚· Identifies the Virtual Machine Manager host group, HGroup2, as the host group for the self-service policy and stores the host group object in variable $VMHostGroup2.
ï‚· Identifies the Active Directory user account or security group to which the self-service policy applies and stores its object in variable $ADUserOrGroup2. The following example uses the Active Directory group, SelfServGroup2, located in the Contoso.com domain.
ï‚· Names the self-service policy and stores the name in variable $Policy2.
ï‚· Specifies a set of self-service policy permissions and stores the permissions object in variable $VmManagementPermissions. In addition to the Vmrc permission that enables self-service users to access a host's virtual machines, the policy grants users permissions to start, stop, pause and resume, and shut down their virtual machines, to create checkpoints for their virtual machines.
Note
ï‚· To see a list of all possible self-service permissions, type the following command on a single line:
ï‚· [enum]::GetValues([Microsoft.VirtualManager.Remoting.SelfServicePermission])
$VMHostGroup2 = Get-VMHostGroup | where { $_.Name -eq "HGroup2" }
$ADUserOrGroup2 = "Contoso\SelfServGroup2"
$Policy2 = "SelfServGroup2 on HGroup2"
$VmManagementPermissions = 'ResumeAndPause','Vmrc','Start','Stop','Shutdown','Checkpoint'
Create a Self-Service Policy for SelfServGroup2
The third command in the script performs the following tasks:
ï‚· Creates and names a self-service policy.
ï‚· Specifies that members of the Active Directory group whose object is stored in $ADUserOrGroup2 (SelfServGroup2) will be governed by the policy.
ï‚· Specifies that the policy applies to virtual machines that are deployed on hosts that belong to the host group whose object is stored in $VMHostGroup2.
ï‚· Grants users who are governed by the policy the permissions stored in variable $VMManagementPermissions.
ï‚· Specifies that all users of the policy share the ownership of the virtual machines that are governed by the policy.
ï‚· Stores the object that represents the new self-service policy in variable $SSPol_VMManage.
####################################################################
# Create a self-service policy for this set of users.
####################################################################
$SSPol_VMManage = New-SelfServicePolicy -Name $Policy2 -UserOrGroup $ADUserOrGroup2 -VMHostGroup $VMHostGroup2 -VMPermission $VmManagementPermissions -SharedVMOwnership $True
Make Virtual Machines Available to SelfServGroup2
The last set of commands in the script performs the following tasks:
ï‚· Gets the objects that represent the set of virtual machines whose name begins with the prefix "SSVM20" and stores the virtual machine objects in variable array $UserVMsSet2.
ï‚· Uses the pipeline operator (|) to pass the objects in $UserVMsSet2 to the Set-VM cmdlet, which sets the members of $ADUserOrGroup2 as owners of the policy $SSPol_VMManage so that the virtual machines available to the group are displayed to its members.
Note
The following example assumes that the set of virtual machines that you want to assign to the group uses the naming convention SSVM200, SSVM202, SSVM203, and so on up to 209.
CreateSelfServicePolicy_ManageVMs.ps1 - Complete Script
Copy the following complete version of CreateSelfServicePolicy_ManageVMs.ps1 into a Notepad file and save it as CreateSelfServicePolicy_Manage.ps1:
# Filename: CreateSelfServicePolicy_ManageVMs.ps1
# Description: Create a self-service policy that grants System Center
# Virtual Machine Manager self-service users a specific
# set of permissions for managing their VMS, and set
# their VMs to be covered by that policy.
# 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:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
####################################################################
# Define variables for CreateSelfServicePolicy__ManageVMs.ps1.
####################################################################
$VMHostGroup2 = Get-VMHostGroup | where { $_.Name -eq "HGroup2" }
$ADUserOrGroup2 = "Contoso\SelfServGroup2"
$Policy2 = "SelfServGroup2 on HGroup2"
$VmManagementPermissions = 'ResumeAndPause','Vmrc','Start','Stop','Shutdown','Checkpoint'
# To see a list of all possible self-service permissions, type:
# [enum]::GetValues([Microsoft.VirtualManager.Remoting.
# SelfServicePermission])
####################################################################
# Create a self-service policy for this set of users.
####################################################################
$SSPol_VMManage = New-SelfServicePolicy -Name $Policy2 -UserOrGroup $ADUserOrGroup2 -VMHostGroup $VMHostGroup2 -VMPermission $VmManagementPermissions -SharedVMOwnership $True
####################################################################
# Find VMs for this group and set the ownership and policy so that
# the VMs available to this group will display to group members.
####################################################################
$UserVMsSet2 = Get-VM -Name "SSVM20*"
$UserVMsSet2 | Set-VM -Owner $ADUserOrGroup2 -SelfServicePolicy $SSPol_VMManage
CreateSelfServicePolicy_CreateManageVMs.ps1
You can use the CreateSelfServicePolicy_CreateManageVMs.ps1 script to create a self-service policy that grants members of an Active Directory group permissions to access, manage, and create up to 10 virtual machines.
How CreateSelfServicePolicy_CreateManageVMs.ps1 Works
The following sections explain each part of the script CreateSelfServicePolicy_CreateManageStoreVMs.ps1.
Connect to the Virtual Machine Manager Server
The first command in the script 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.
####################################################################
# Substitute the name of your VMM server and domain in this command:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
Define Variables for CreateSelfServicePolicy_CreateManageVMs.ps1
The second set of commands in the script performs the following tasks:
ï‚· Identifies the Virtual Machine Manager host group, HGroup3, as the host group for the self-service policy and stores the host group object in variable $VMHostGroup3.
ï‚· Identifies the Active Directory user account or security group to which the self-service policy applies and stores its object in variable $ADUserOrGroup3. The following example uses the Active Directory group, SelfServGroup3, located in the Contoso.com domain.
ï‚· Names the self-service policy and stores the name in variable $Policy3.
ï‚· Specifies a set of self-service policy permissions and stores the permissions object in variable $VMCreationPermissions. In addition to the Vmrc permission that enables self-service users to access a host's virtual machines, the policy grants users permissions to create, start, stop, pause and resume, remove, and shut down their virtual machines. The policy also grants users the permission to create checkpoints for their virtual machines and to act as local Administrators on their virtual machines.
Note
ï‚· To see a list of all possible self-service permissions, type the following command on a single line:
ï‚· [enum]::GetValues([Microsoft.VirtualManager.Remoting.SelfServicePermission])
ï‚· Gets the objects that represent all virtual machine templates available in your Virtual Machine Manager environment and stores the template objects in the variable array $TemplateList.
Note
Self-service users who are granted permission to create virtual machines need access to at least one template; the following example assumes that multiple templates exist and that you want to allow self-service users access to all templates.
ï‚· Specifies a quota limit of 8 for users who are governed by the self-service policy. The quota limits the number of virtual machines that a user or group can create.
####################################################################
# Define variables for CreateSelfServicePolicy_ManageVMs.ps1.
####################################################################
$VMHostGroup3 = Get-VMHostGroup | where { $_.Name -eq "HGroup3" }
$ADUserOrGroup3 = "Contoso\SelfServGroup3"
$Policy3 = "SelfServGroup3 on HGroup3"
$VMCreationPermissions = 'Create','ResumeAndPause','Vmrc','Start','Stop','Remove','Shutdown','Checkpoint','AllowLocalAdmin'
$TemplateList = Get-Template
$QuotaLimit = 8
Create a Self-Service Policy for SelfServGroup3
The third command in the script performs the following tasks:
ï‚· Creates and names a self-service policy.
ï‚· Specifies that members of the Active Directory group whose object is stored in $ADUserOrGroup3 (SelfServGroup3) are governed by the policy.
ï‚· Specifies that the policy applies to virtual machines that are deployed on hosts that belong to the host group (HGroup3) whose object is stored in $VMHostGroup3.
ï‚· Grants users who are governed by the policy the permissions that are stored in variable $VMCreationPermissions.
ï‚· Specifies that all users of the policy share the ownership of the virtual machines that are governed by the policy.
ï‚· Specifies that all users of the policy can use the templates stored in $TemplateList to create virtual machines.
ï‚· Specifies the quota limit stored in $QuotaLimit.
ï‚· Stores the object that represents the new self-service policy in variable $SSPol_VMCreate.
####################################################################
# Create a self-service policy for this set of users.
####################################################################
$SSPol_VMCreate = New-SelfServicePolicy -Name $Policy3 -UserOrGroup $ADUserOrGroup3 -VMHostGroup $VMHostGroup3 -VMPermission $VMCreationPermissions -SharedVMOwnership $True -Template $TemplateList -QuotaPoint $QuotaLimit
Make Virtual Machines Available to SelfServGroup3
The last set of commands in the script performs the following tasks:
ï‚· Gets the objects that represent the set of virtual machines whose name begins with the prefix "SSVM30" and stores the virtual machine objects in variable array $UserVMsSet3.
ï‚· Uses the pipeline operator (|) to pass the objects in $UserVMsSet3 to the Set-VM cmdlet, which sets the members of $ADUserOrGroup3 as owners of the policy $SSPol_VMCreate so that the virtual machines available to the group are displayed to its members.
Note
The following example assumes that the set of virtual machines that you want to assign to the group uses the naming convention SSVM300, SSVM302, SSVM303, and so on up to 309.
####################################################################
# Find VMs for this group and set the ownership and policy so that
# the VMs available to this group will display to group members.
####################################################################
$UserVMsSet3 = Get-VM -Name "SSVM30*"
$UserVMsSet3 | Set-VM -Owner $ADUserOrGroup3 -SelfServicePolicy $SSPol_VMCreate
CreateSelfServicePolicy_CreateManageVMs.ps1 - Complete Script
Copy the following complete version of CreateSelfServicePolicy_CreateManageVMs.ps1 into a Notepad file and save it as CreateSelfServicePolicy_CreateManageVMs.ps1:
# Filename: CreateSelfServicePolicy_CreateManageVMs.ps1.
# Description: Create a self-service policy that grants System Center
# Virtual Machine Manager self-service users permission
# to create and manage their VMs, and set their VMs to be
# covered by that policy.
# 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:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
####################################################################
# Define variables for CreateSelfServicePolicy_ManageVMs.ps1
####################################################################
$VMHostGroup3 = Get-VMHostGroup | where { $_.Name -eq "HGroup3" }
$ADUserOrGroup3 = "Contoso\SelfServGroup3"
$Policy3 = "SelfServGroup3 on HGroup3"
$VMCreationPermissions = 'Create','ResumeAndPause','Vmrc','Start','Stop','Remove','Shutdown','Checkpoint','AllowLocalAdmin'
# To see a list of all possible self-service permissions, type:
# [enum]::GetValues([Microsoft.VirtualManager.Remoting.
# SelfServicePermission])
$TemplateList = Get-Template
$QuotaLimit = 8
####################################################################
# Create a self-service policy for this set of users.
####################################################################
$SSPol_VMCreate = New-SelfServicePolicy -Name $Policy3 -UserOrGroup $ADUserOrGroup3 -VMHostGroup $VMHostGroup3 -VMPermission $VMCreationPermissions -SharedVMOwnership $True -Template $TemplateList -QuotaPoint $QuotaLimit
####################################################################
# Find VMs for this group and set the ownership and policy so that
# the VMs available to this group will display to group members.
####################################################################
$UserVMsSet3 = Get-VM -Name "SSVM30*"
$UserVMsSet3 | Set-VM -Owner $ADUserOrGroup3 -SelfServicePolicy $SSPol_VMCreate
CreateSelfServicePolicy_CreateManageStoreVMs.ps1
You can use the CreateSelfServicePolicy_CreateManageStore.ps1 script to create a self-service policy that grants members of an Active Directory group permissions to access, manage, and create up to 10 virtual machines and also to store their virtual machines in the Virtual Machine Manager library.
How CreateSelfServicePolicy_CreateManageStoreVMs.ps1 Works
The following sections explain each part of the script CreateSelfServicePolicy_CreateManageStoreVMs.ps1.
Connect to the Virtual Machine Manager Server
The first command in the script 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
####################################################################
# Substitute the name of your VMM server and domain in this command:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
Define Variables for CreateSelfServicePolicy_CreateManageStoreVMs.ps1
The second set of commands in the script performs the following tasks:
ï‚· Identifies the Virtual Machine Manager host group, HGroup4, as the host group for the self-service policy and stores the host group object in variable $VMHostGroup4.
ï‚· Identifies the Active Directory user account or security group to which the self-service policy applies and stores its object in variable $ADUserOrGroup4. The following example uses the Active Directory group, SelfServGroup4, located in the Contoso.com domain.
ï‚· Names the self-service policy and stores the name in variable $Policy4.
ï‚· Specifies a set of self-service policy permissions and stores the permissions object in variable $AllPermissions. In addition to the Vmrc permission that enables self-service users to access a host's virtual machines, the policy grants users permissions to create, start, stop, pause and resume, remove, and shut down their virtual machines. The policy also grants users the permission to create checkpoints for their virtual machines, to act as local Administrators on their virtual machines, and to store their virtual machines in the Virtual Machine Manager library.
Note
ï‚· To see a list of all possible self-service permissions, type the following command on a single line:
ï‚· [enum]::GetValues([Microsoft.VirtualManager.Remoting.SelfServicePermission])
ï‚· Gets the objects that represent all virtual machine templates that are available in your Virtual Machine Manager environment and stores the template objects in the variable array $TemplateList.
Note
Self-service users who are granted permission to create virtual machines need access to at least one template; the following example assumes that multiple templates exist and that you want to allow self-service users access to all templates.
ï‚· Specifies a quota limit of 10 for users who are governed by the self-service policy. The quota limits the number of virtual machines that a user or group can create.
ï‚· Specifies the path to the Virtual Machine Manager library share called "Self Service".
Note
Users granted the "store" permission can store their virtual machines in the library, which requires that a library share path for the policy is specified. The following example assumes that a library share named "Self Service" already exists.
#######################################################################
# Define variables for CreateSelfServicePolicy_CreateManageStoreVMs.ps1
#######################################################################
$VMHostGroup4 = Get-VMHostGroup | where { $_.Name -eq "HGroup4" }
$ADUserOrGroup4 = "Contoso\SelfServGroup4"
$Policy4 = "SelfServGroup4 on HGroup4"
$AllPermissions = 'Create','ResumeAndPause','Vmrc','Start','Stop','Remove','Shutdown','Checkpoint','Store','AllowLocalAdmin'
$TemplateList = Get-Template
$QuotaLimit = 10
$LibraryPath = "\\VMMServer1.Contoso.com\MSSCVMMLibrary\Self Service"
Create a Self-Service Policy for SelfServGroup4
The third command in the script performs the following tasks:
ï‚· Creates and names a self-service policy.
ï‚· Specifies that members of the Active Directory group whose object is stored in $ADUserOrGroup4 (SelfServGroup4) are governed by the policy.
ï‚· Specifies that the policy applies to virtual machines that are deployed on hosts that belong to the host group (HGroup4) whose object is stored in $VMHostGroup4.
ï‚· Grants users who are governed by the policy the permissions that are stored in variable $AllPermissions.
ï‚· Specifies that all users of the policy share the ownership of the virtual machines that are governed by the policy.
ï‚· Specifies that all users of the policy can use the templates stored in $TemplateList to create virtual machines.
ï‚· Specifies the quota limit stored in $QuotaLimit.
ï‚· Specifies that the share on a library server where users of the policy can store their virtual machines is the share whose path is stored in variable $LibraryPath.
ï‚· Stores the object that represents the new self-service policy in variable $SSPol_All.
####################################################################
# Create a self-service policy for this set of users.
####################################################################
$SSPol_All = New-SelfServicePolicy -Name $Policy4 -UserOrGroup $ADUserOrGroup4 -VMHostGroup $VMHostGroup4 -VMPermission $AllPermissions -SharedVMOwnership $True -Template $TemplateList -QuotaPoint $QuotaLimit -LibraryStoreSharePath $LibraryPath
Make Virtual Machines Available to SelfServGroup4
The last set of commands in the script performs the following tasks:
ï‚· Gets the objects that represent the set of virtual machines whose name begins with the prefix "SSVM40" and stores the virtual machine objects in variable array $UserVMsSet4.
ï‚· Uses the pipeline operator (|) to pass the objects in $UserVMsSet4 to the Set-VM cmdlet, which sets the members of $ADUserOrGroup4 as owners of the policy $SSPol_All so that the virtual machines available to the group are displayed to its members.
Note
The following example assumes that the set of virtual machines that you want to assign to the group uses the naming convention SSVM400, SSVM402, SSVM403, and so on up to 409.
####################################################################
# Find VMs for this group and set the ownership and policy so that
# the VMs available to this group will display to group members.
####################################################################
$UserVMsSet4 = Get-VM -Name "SSVM40*"
$UserVMsSet4 | Set-VM -Owner $ADUserOrGroup4 -SelfServicePolicy $SSPol_All
CreateSelfServicePolicy_CreateManageStoreVMs.ps1 - Complete Script
Copy the following complete version of CreateSelfServicePolicy_CreateManageStoreVMs.ps1 into a Notepad file and save it as CreateSelfServicePolicy_CreateManageStoreVMs.ps1:
# Filename: CreateSelfServicePolicy_CreateManageStoreVMs.ps1
# Description: Create a self-service policy that grants System Center
# Virtual Machine Manager self-service users permission
# to create, manage, and store their VMS, and set their
# VMs to be covered by that policy.
# 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:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
#######################################################################
# Define variables for CreateSelfServicePolicy_CreateManageStoreVMs.ps1
#######################################################################
$VMHostGroup4 = Get-VMHostGroup | where { $_.Name -eq "HGroup4" }
$ADUserOrGroup4 = "Contoso\SelfServGroup4"
$Policy4 = "SelfServGroup4 on HGroup4"
$AllPermissions = 'Create','ResumeAndPause','Vmrc','Start','Stop','Remove','Shutdown','Checkpoint','Store','AllowLocalAdmin'
# To see a list of all possible self-service permissions, type:
# [enum]::GetValues([Microsoft.VirtualManager.Remoting.
# SelfServicePermission])
$TemplateList = Get-Template
$QuotaLimit = 10
$LibraryPath = "\\VMMServer1.Contoso.com\MSSCVMMLibrary\Self Service"
####################################################################
# Create a self-service policy for this set of users.
####################################################################
$SSPol_All = New-SelfServicePolicy -Name $Policy4 -UserOrGroup $ADUserOrGroup4 -VMHostGroup $VMHostGroup4 -VMPermission $AllPermissions -SharedVMOwnership $True -Template $TemplateList -QuotaPoint $QuotaLimit -LibraryStoreSharePath $LibraryPath
####################################################################
# Find VMs for this group and set the ownership and policy so that
# the VMs available to this group will display to group members.
####################################################################
$UserVMsSet4 = Get-VM -Name "SSVM40*"
$UserVMsSet4 | Set-VM -Owner $ADUserOrGroup4 -SelfServicePolicy $SSPol_All
Sample Scripts for Backing Up and Restoring the VMM Database
You can experiment with the Windows PowerShell scripts in this topic to learn how to back up and restore the Virtual Machine Manager database. The scripts differ depending on where the database is stored:
 Locally. On the Virtual Machine Manager server itself (if the server is running either Microsoft SQL Server 2005 Express Edition SP1 or Microsoft SQL Server 2005)
 Remotely. On a remote server running SQL Server 2005
Note
These scripts back up and restore the Virtual Machine Manager database. If you want to back up and restore the Virtual Machine Manager server itself (or a server functioning as a virtual machine host or as a library server), use your standard server backup procedure.
Backup/Recover: What You Need to Know Before You Start
It is possible that the SQL Server service (either SQL Server 2005 Express Edition SP1 or SQL Server 2005) is installed on the Virtual Machine Manager server but is not used to store the Virtual Machine Manager database. If you do not know whether the Virtual Machine Manager database is stored locally or on a remote server running SQL Server 2005, use the following procedure.
To determine whether the VMM database is stored locally or remotely
1. Open the Registry Editor. 2. Navigate to the following subkey: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft System Center Virtual Machine Manager 2007 Server\Settings\Sql 3. View the value for OnRemoteServer: ï‚· If OnRemoteServer is set to 0, the database is on the local Virtual Machine Manager server. ï‚· If OnRemoteServer is set to 1, the database is on a remote server running the SQL Server service. |
BackupLocalVMM.ps1
You can use the BackupLocalVMM.ps1 script to back up the Virtual Machine Manager database if the database is stored locally on the Virtual Machine Manager server.
How BackupLocalVMM.ps1 Works
The first command in the script connects to VMMServer1 in the Contoso.com domain, retrieves the server object from the Virtual Machine Manager database, and stores the server object in variable $VMMServer:
$VMMServer = Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
The second command in the script uses the Backup-VMMServer cmdlet to back up the Virtual Machine Manager database stored on VMMServer1 to C:\VMMBackups on VMMServer1:
Backup-VMMServer -Path "C:\VMMBackups" -VMMServer $VMMServer
The destination path (C:\VMMBackups in the following example) must be on a server that stores the Virtual Machine Manager database. The server must be running SQL Server 2005 or SQL Server 2005 Express Edition SP1. The following example assumes that SQL Server is installed on VMMServer1 rather than on a remote server.
BackupLocalVMM.ps1 - Complete Script
Copy the following complete version of BackupLocalVMM.ps1 into a Notepad file, and save it as BackupLocalVMM.ps1.
# Filename: BackupLocalVMM.ps1
# Description: Backs up the VMM database when the database
# is stored locally on the VMM server.
# 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.
# Substitute the name of your VMM server and domain in this command:
$VMMServer = Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
# Substitute your backup folder path and name for C:\VMMBackups:
Backup-VMMServer -Path "C:\VMMBackups" -VMMServer $VMMServer
BackupRemoteVMM.ps1
You can use the BackupRemoteVMM.ps1 script to back up the Virtual Machine Manager database if the database is stored on a remote server that is running SQL Server 2005.
How BackupRemoteVMM.ps1 Works
The first command in the script connects to VMMServer1 in the Contoso.com domain, retrieves the server object from the Virtual Machine Manager database, and stores the server object in variable $VMMServer:
$VMMServer = Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
The second command in the script uses a network share (instead of a local folder as in BackupLocalVMM.ps1 example script) as the destination path. The command backs up the Virtual Machine Manager database that is stored on SQLServer01 to the VMMBackups share on SQLServer01:
Backup-VMMServer -Path "\\SQLServer01\VMMBackups" -VMMServer $VMMServer
The destination path (\\SQLServer01\VMMBackups in the following example) must be on a server that stores the Virtual Machine Manager database and is running SQL Server 2005. The following example assumes that SQL Server 2005 is installed on a remote server, called SQLServer01, that stores the Virtual Machine Manager database managed by VMMServer1.
BackupRemoteVMM.ps1 - Complete Script
Copy the following complete version of BackupRemoteVMM.ps1 into a Notepad file, and save it as BackupRemoteVMM.ps1.
# Filename: BackupRemoteVMM.ps1
# Description: Backs up the VMM database when the database
# is stored on a remote SQL Server.
# 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.
# Substitute the name of your VMM server and domain in this command:
$VMMServer = Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
# Substitute your backup folder path and name for
# \\SQLServer01\VMMBackups in this command:
Backup-VMMServer -Path "\\SQLServer01\VMMBackups" -VMMServer $VMMServer
RestoreLocalVMM.ps1
To restore the Virtual Machine Manager database after it was backed up locally, you must use the SCVMMRecover.exe command that is installed with Virtual Machine Manager. SCVMMRecover.exe is not a Windows PowerShell cmdlet.
How RestoreLocalVMM.ps1 Works
The following example script assumes that:
ï‚· SCVMMRecover.exe is located in the default location for Virtual Machine Manager at C:\Program Files\Microsoft System Center Virtual Machine Manager 2007\bin\. The folder to which the database was backed up is the same folder (C:\VMMBackups) that is used in the BackupLocalVMM.ps1 example script.
ï‚· The backup file name is VirtualManagerDB-07022007-233717.bak.
You must run SCVMMRecover.exe locally on the Virtual Machine Manager server to which you want to restore the database:
& 'C:\Program Files\Microsoft System Center Virtual Machine Manager 2007\bin\SCVMMRecover.exe' -Path 'C:\VMMBackups\VirtualManagerDB-07022007-233717.bak'
When you see the message "SCVMMRecover will replace the existing Virtual Machine Manager database with the backed up database. Do you want to continue?," type Y and then press ENTER to restore the Virtual Machine Manager database. If the operation is completed successfully, the message "VMM database recovery completed" appears.
RestoreLocalVMM.ps1 - Complete Script
Copy the following complete version of RestoreLocalVMM.ps1 into a Notepad file and save it as RestoreLocalVMM.ps1.
# Filename: RestoreLocalVMM.ps1
# Description: Restores the Virtual Machine Manager database backed up
# locally by using the Backup-VMMServer cmdlet.
# 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.
# This example script assumes that SCVMMRecover.exe is located in the
# default location for Virtual Machine Manager at:
# C:\Program Files\
# Microsoft System Center Virtual Machine Manager 2007\bin\
# Substitute your backup folder and path for C:\VMMBackups, and
# substitute the actual backup file name for
# VirtualManagerDB-07022007-233717.bak
& 'C:\Program Files\Microsoft System Center Virtual Machine Manager 2007\bin\SCVMMRecover.exe' -Path 'C:\VMMBackups\VirtualManagerDB-07022007-233717.bak'
RestoreRemoteVMM.ps1
To restore the Virtual Machine Manager database after it was backed up remotely, you must use the SCVMMRecover.exe command that is installed with Virtual Machine Manager. SCVMMRecover.exe is not a Windows PowerShell cmdlet.
How RestoreRemoteVMM.ps1 Works
The following example script assumes that:
ï‚· SCVMMRecover.exe is located in the default location for Virtual Machine Manager at C:\Program Files\Microsoft System Center Virtual Machine Manager 2007\bin\.
ï‚· The remote share to which the database was backed up is the same share (\\SQLServer01\VMMBackups) that is used in the BackupRemoteVMM.ps1 example script.
ï‚· The backup file name is VirtualManagerDB-07022007-233718.bak.
You must run SCVMMRecover.exe locally on the Virtual Machine Manager server to which you want to restore the database:
& 'C:\Program Files\Microsoft System Center Virtual Machine Manager 2007\bin\SCVMMRecover.exe' -Path "\\SQLServer01\VMMBackups\VirtualManagerDB-07022007-233718.bak"
When you see the message "SCVMMRecover will replace the existing Virtual Machine Manager database with the backed up database. Do you want to continue?," type Y and then press ENTER to restore the Virtual Machine Manager database. If the operation is completed successfully, the message "VMM database recovery completed" appears.
RestoreRemoteVMM.ps1 - Complete Script
Copy the following complete version of RestoreRemoteVMM.ps1 into a Notepad file, and save it as RestoreRemoteVMM.ps1.
# Filename: RestoreRemoteVMM.ps1
# Description: Restores the Virtual Machine Manager database that was
# backed up (on the remote SQL Server on which the database resides)
# by using the Backup-VMMServer cmdlet.
# 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.
# This example script assumes that SCVMMRecover.exe is located in the
# default location for Virtual Machine Manager at:
# C:\Program Files\
# Microsoft System Center Virtual Machine Manager 2007\bin\
# Substitute your backup folder path and name for
# \\SQLServer01\VMMBackups
# and substitute the actual backup file name
# for VirtualManagerDB-07022007-233718.bak
& 'C:\Program Files\Microsoft System Center Virtual Machine Manager 2007\bin\SCVMMRecover.exe' -Path "\\SQLServer01\VMMBackups\VirtualManagerDB-07022007-233718.bak"
Sample Script for Integrating VMM with OpsMgr
If your network environment includes both System Center Operations Manager and Virtual Machine Manager, you can experiment with the Windows PowerShell script described in this topic to learn how to script Operations Manager discovery of computers that are managed by Virtual Machine Manager.
DiscoverVMMComputers.ps1
Operations Manager can provide end-to-end monitoring of computers that it manages to ensure the health and availability of those computers. For this reason, if your organization has deployed both Operations Manager and Virtual Machine Manager, you should ensure that Operations Manager discovers your Virtual Machine Manager host servers and library servers and incorporates them in the set of computers that is monitored by Operations Manager.
How DiscoverVMMComputers.ps1 Works
The DiscoverVMMComputers.ps1 script performs the tasks described in the following sections.
Connect to the Virtual Machine Manager Server
The first command in DiscoverVMMComputers.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
####################################################################
# Substitute the name of your VMM server and domain in this command:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
Get All Computers Managed by VMM and Get the Operations Manager Server
Next, the DiscoverVMMComputers.ps1 script gets all the Virtual Machine Manager computers and the Operations Manager server that you want to use to manage those computers:
ï‚· The script uses the VMM cmdlet, Get-VMMManagedComputer, to get the objects that represents all computers managed by Virtual Machine Manager (all virtual machine hosts and all library servers), and stores those computer objects in variable $VMMManagedComputer.
ï‚· The script uses the Operations Manager cmdlet, Get-ManagementServer, to get the object from the Operations Manager database that represents the Operations Manager Management Server, and stores the Management Server object in variable $OpsMgrServer.
####################################################################
# Get all computers managed by VMM and get OpsMgr server
####################################################################
# Get the object for all host and library servers managed by VMM
$VMMManagedComputer = Get-VMMManagedComputer
# Get an instance of the OpsMgr Management Server
$OpsMgrServer = Get-ManagementServer
Add Each VMM-Managed Computer to Operations Manager
Finally, the DiscoverVMMComputers.ps1 script uses a ForLoop to perform the following tasks:
ï‚· Loops through each object in $VMMManagedComputer, in turn.
ï‚· Uses the Operations Manager cmdlet, New-WindowsDiscoveryConfiguration, to create a Windows discovery configuration object for each managed computer and stores the configuration object for each computer in variable $DiscoveryConfig.
Note
A Windows discovery configuration object describes a computer so that information about that computer can be discovered by the Start-Discovery cmdlet.
ï‚· Passes the configuration objects that are stored in variable $DiscoveryConfig to the Operations Manager cmdlet, Start-Discovery, which adds the hosts and library servers that are managed by Virtual Machine Manager to the set of computers that is monitored by Operations Manager.
####################################################################
# For each VMM host and library server, initiate a discovery
####################################################################
ForEach ($Computer in $VMMManagedComputer)
{
#Create a new discovery configuration
$DiscoveryConfig = New-WindowsDiscoveryConfiguration -ComputerName $Computer.Name -ComputerType Server
#Initiate the Operations Manager discovery
Start-Discovery -ManagementServer $OpsMgrServer -WindowsDiscoveryConfiguration $DiscoveryConfig
}
DiscoverVMMComputers.ps1 - Complete Script
Copy the following complete version of DiscoverVMMComputers.ps1 into a Notepad file and save it as DiscoverVMMComputers.ps1:
# Filename: DiscoverVMMComputers.ps1.ps1
# Description: Adds System Center Virtual Machine Manager host servers
# and library servers to the set of computers managed
# by System Center Operations Manager.
# 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:
Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
####################################################################
# Get all computers managed by VMM and get OpsMgr server
####################################################################
# Get the object for all host and library servers managed by VMM
$VMMManagedComputer = Get-VMMManagedComputer
# Get an instance of the OpsMgr Management Server
$OpsMgrServer = Get-ManagementServer
####################################################################
# For each VMM host and library server, initiate a discovery
####################################################################
ForEach ($Computer in $VMMManagedComputer)
{
#Create a new discovery configuration
$DiscoveryConfig = New-WindowsDiscoveryConfiguration -ComputerName $Computer.Name -ComputerType Server
#Initiate the Operations Manager discovery
Start-Discovery -ManagementServer $OpsMgrServer -WindowsDiscoveryConfiguration $DiscoveryConfig
}
Sample Script Summarizing VMM Information
You can experiment with the Windows PowerShell script SummarizeVMMInformation.ps1 to learn how to display a summary of information about your Virtual Machine Manager environment. This script demonstrates how to display a variety of information about the Virtual Machine Manager server, host and library servers, host groups, virtual machines, and self-service policies.
SummarizeVMMInformation.ps1
The following sections describe each set of commands that make up the SummarizeVMMInformation.ps1 script.
Display Information About the Virtual Machine Manager Server
The first set of commands in SummarizeVMMInformation.ps1 performs the following tasks:
1. Retrieves today's date from the system and stores the date in variable $SummaryDate.
2. Connects to the Virtual Machine Manager server, VMMServer1, in the Contoso.com domain, retrieves the server object from the Virtual Machine Manager database, and stores the server object in variable $VMMServer.
3. Retrieves, from the Virtual Machine Manager database, the Virtual Machine Manager host objects as an array and stores the host objects in variable $VMHosts.
4. Retrieves, from the Virtual Machine Manager database, all virtual machine objects and uses the pipeline operator (|) and where statement to select only objects for virtual machines that are not stored in the library. The command stores these virtual machine objects in variable $HostedVMs.
5. Displays the following summary information about your Virtual Machine Manager server and its hosts and virtual machines:
ï‚· Today's date.
ï‚· The name of the Virtual Machine Manager server.
ï‚· Whether this is an evaluation version of the Virtual Machine Manager software.
ï‚· The placement goal (the two possible values are LoadBalance or Consolidate) that Virtual Machine Manager uses to select the most suitable host on which to deploy a virtual machine. LoadBalance refers to load balancing among hosts, which minimizes the processing load on any one host. Consolidate refers to resource maximization on individual hosts, which consolidates multiple low-utilization workloads on a single host.
ï‚· The number of hosts added to this Virtual Machine Manager server.
ï‚· The number of virtual machines deployed on any host.
ï‚· The average number of virtual machines per host.
####################################################################
# Summary of Virtual Machine Manager Server
####################################################################
$SummaryDate = Get-Date
# Substitute the name of your VMM server and domain in this command:
$VMMServer = Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
$VMHosts = @(Get-VMHost)
$HostedVMs = @(Get-VM | where {$_.Status -ne "Stored"})
Write-Host "`nVIRTUAL MACHINE MANAGER SERVER" -ForegroundColor Yellow
Write-Host "Summary Date :", $SummaryDate
Write-Host "VMM Server Name :", $VMMServer.Name
Write-Host "Evaluation Version :", $VMMServer.IsEvaluationVersion
Write-Host "Placement Goal :", $VMMServer.PlacementGoal
Write-Host "Total Hosts :", $VMHosts.Count
Write-Host "Hosted VMs :", $HostedVMs.Count
if ($VMHosts.Count -ne 0)
{
Write-Host "VMs per Host :", ($HostedVMs.Count / $VMHosts.Count)
}
Display Information About Host Servers
The next set of commands performs the following tasks:
1. Retrieves, from the Virtual Machine Manager database, all Virtual Machine Manager host objects as an array and stores the host objects in variable $VMHosts.
2. Displays the following summary information about your virtual machine hosts, using the pipeline operator (|) and where statement to filter host objects based on specific criteria:
ï‚· The total number of hosts.
ï‚· The number of hosts that are not responding.
ï‚· The total number of hosts on which you need to install an updated version of the Virtual Machine Manager agent software.
 The total number of hosts on which you need to install an updated version of the Microsoft Virtual Server 2005 software.
ï‚· The number of hosts that are categorized as maintenance hosts. A maintenance host is a host that you can dedicate for patching stored resources and for staging virtual machines before you move them into your production environment.
ï‚· The number of hosts that are located in a perimeter network.
####################################################################
# Summary of Virtual Machine Hosts
####################################################################
$VMHosts = @(Get-VMHost)
Write-Host "`nVIRTUAL MACHINE HOSTS" -ForegroundColor Yellow
Write-Host "Total Hosts :", $VMHosts.Count
Write-Host "Hosts Not Responding :", @($VMHosts | where {$_.Status -eq "NotResponding"}).Count
Write-Host "Hosts Needing Agent Update :", @($VMHosts | where {$_.Agent.VersionState -eq "NeedsUpdate"}).Count
Write-Host "Hosts Needing Virtual Server Update :", @($VMHosts | where {$_.VirtualServerVersionState -eq "NeedsUpdate"}).Count
Write-Host "Hosts in Maintenance :", @($VMHosts | where {$_.MaintenanceHost -eq $true}).Count
Write-Host "Hosts on Perimeter Network :", @($VMHosts | where {$_.PerimeterNetworkHost -eq $true}).Count
Display Information About Virtual Machines
The next set of commands performs the following tasks:
1. Retrieves, from the Virtual Machine Manager database, all virtual machine objects as an array and stores the virtual machine objects in variable $VMs.
2. Displays the following summary information about your virtual machines, using the pipeline operator (|) and where statement to filter virtual machine objects based on specific criteria:
ï‚· The total number of virtual machines.
ï‚· The number of virtual machines that are currently deployed on host servers.
ï‚· The number of virtual machines that are currently stored in the Virtual Machine Manager library.
ï‚· The number of virtual machines that are currently running.
ï‚· The number of virtual machines that are currently available for self-service users.
ï‚· The number of virtual machines on which Virtual Manager Additions is not installed.
####################################################################
# Summary of Virtual Machines
####################################################################
$VMs = @(Get-VM)
Write-Host "`nVIRTUAL MACHINES" -ForegroundColor Yellow
Write-Host "Total VMs :", $VMs.Count
Write-Host "Hosted VMs :", @($VMs | where {$_.Status -ne "Stored"}).Count
Write-Host "Stored VMs :", @($VMs | where {$_.Status -eq "Stored"}).Count
Write-Host "Running VMs :", @($VMs | where {$_.Status -eq "Running"}).Count
Write-Host "Self-Service VMs :", @($VMs | where {$_.SelfServicePolicy -ne $null}).Count
Write-Host "VMs without VMAdditions :", @($VMs | where {$_.HasVMAdditions -eq $false}).Count
Display Information About Self-Service Policies
The next set of commands performs the following tasks:
1. Retrieves, from the Virtual Machine Manager database, self-service policy objects as an array and stores the policy objects in variable $SelfServicePolicies. A self-service policy allows a user or members of a group to create and manage their own virtual machines through the Virtual Machine Manager self-service feature. Self-service users manage their virtual machines through a Web site called the Self-Service Portal.
2. Displays the following summary information about virtual machines that are available to self-service users, using the pipeline operator (|) and where statement to filter virtual machine objects based on specific criteria:
ï‚· The total number of self-service policies.
ï‚· The total number of virtual machines that are available for self-service users.
ï‚· The number of virtual machines that are assigned to self-service users and are currently deployed on a host server.
ï‚· The total number of virtual machines that are assigned to self-service users and that are currently stored in the Virtual Machine Manager library. These virtual machines are unavailable to self-service users unless the self-service policy that governs these machines includes the permission that allows users to store their virtual machines in the library. The store permission also enables users to deploy a stored virtual machine on a host server (unless the quota-points setting blocks the deployment of additional virtual machines).
####################################################################
# Summary of Self-Service
####################################################################$Se$SelfServicePolicies = @(Get-SelfServicePolicy)
$VMs = @(Get-VM)
Write-Host "`nSELF-SERVICE" -ForegroundColor Yellow
Write-Host "Self Service Policies :", $SelfServicePolicies.Count
Write-Host "Total Self-Service VMs :", @($VMs | where {$_.SelfServicePolicy -ne $null}).Count
Write-Host "Hosted Self-Service VMs :", @($VMs | where {$_.SelfServicePolicy -ne $null} | where {$_.Status -ne "Stored"}).Count
Write-Host "Stored Self-Service VMs :", @($VMs | where {$_.SelfServicePolicy -ne $null} | where {$_.Status -eq "Stored"}).Count
Display Information About Library Servers
The next set of commands in SummarizeVMMInformation.ps1 performs the following tasks:
1. Retrieves, from the Virtual Machine Manager database, all library server objects and stores the library server objects in variable $LibraryServers.
2. Retrieves, from the Virtual Machine Manager database, all virtual machine objects as an array and stores the virtual machine objects in variable $VMs.
3. Displays the number of library servers and the number of virtual machines that are stored in the Virtual Machine Manager library.
####################################################################
# Summary of Library Servers
####################################################################
$LibraryServers = @(Get-LibraryServer)
$VMs = @(Get-VM)
Write-Host "`nLIBRARY SERVERS" -ForegroundColor Yellow
Write-Host "Library Servers :", $LibraryServers.Count
Write-Host "Stored VMs :", ($VMs | where {$_.Status -eq "Stored"}).Count
Display Information About Host Groups
The final set of commands in SummarizeVMMInformation.ps1 performs the following tasks:
1. Retrieves, from the Virtual Machine Manager database, all virtual machine host groups as an array and stores the host group objects in variable $VMHostGroups.
2. Retrieves, from the Virtual Machine Manager database, all virtual machine objects as an array and stores the virtual machine objects in variable $VMs.
3. For each host group, determines the following:
ï‚· The number of hosts in the host group.
ï‚· The number of virtual machines in the host group.
ï‚· The number of running virtual machines on hosts in the host group.
ï‚· The number of virtual machines that are allocated to self-service users in the host group.
4. Displays the following information about each host group:
ï‚· The name of the host group.
ï‚· The number of hosts in the host group.
ï‚· The number of virtual machines, running virtual machines, and self-service virtual machines in the host group.
ï‚· The number of virtual machines on each host ($VMCount / $VMHostCount); the number of running virtual machines on each host ($RunningVMCount / $VMHostCount), and the number of self-service virtual machines on each host ($SelfServiceVMCount / $VMHostCount).
####################################################################
# Summary of Virtual Machine Host Groups
####################################################################
$VMHostGroups = @(Get-VMHostGroup)
$VMs = @(Get-VM)
Write-Host "`nVIRTUAL MACHINE HOST GROUPS" -ForegroundColor Yellow
foreach ($VMHostGroup in $VMHostGroups)
{
$VMHostCount = $VMHostGroup.Hosts.Count
$VMCount = @($VMs | where {$VMHostGroup.Hosts -contains $_.VMHost}).Count
$RunningVMCount = @($VMs | where {$VMHostGroup.Hosts -contains $_.VMHost} | where {$_.Status -eq "Running"}).Count
$SelfServiceVMCount = @($VMs | where {$VMHostGroup.Hosts -contains $_.VMHost} | where {$_.SelfServicePolicy -ne $null}).Count
Write-Host "Host Group :", $VMHostGroup.Name
Write-Host "Number of Hosts :", $VMHostCount
if ($VMHostCount -ne 0)
{
Write-Host "Number of VMS :", $VMCount
Write-Host "Running VMs :", $RunningVMCount
Write-Host "Self-Service VMs :", $SelfServiceVMCount
Write-Host "VMs per Host :", ($VMCount / $VMHostCount)
Write-Host "Running VMs per Host :", ($RunningVMCount / $VMHostCount)
Write-Host "Self-Serice VMs per Host :", ($SelfServiceVMCount / $VMHostCount)
}
Write-Host
}
SummarizeVMMInformation.ps1 - Complete Script
Copy the following complete version of SummarizeVMMInformation.ps1 into a Notepad file, and save it as SummarizeVMMInformation.
# Filename: SummarizeVMMInformation.ps1
# Description: Display information about Virtual Machine Manager
# servers (including hosts and library servers),
# host groups, virtual machines, and self-service
# policies.
# 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.
####################################################################
# Summary of Virtual Machine Manager Server
####################################################################
$SummaryDate = Get-Date
# Substitute the name of your VMM server and domain in this command:
$VMMServer = Get-VMMServer -ComputerName "VMMServer1.Contoso.com"
$VMHosts = @(Get-VMHost)
$HostedVMs = @(Get-VM | where {$_.Status -ne "Stored"})
Write-Host "`nVIRTUAL MACHINE MANAGER SERVER" -ForegroundColor Yellow
Write-Host "Summary Date :", $SummaryDate
Write-Host "VMM Server Name :", $VMMServer.Name
Write-Host "Evaluation Version :", $VMMServer.IsEvaluationVersion
Write-Host "Placement Goal :", $VMMServer.PlacementGoal
Write-Host "Total Hosts :", $VMHosts.Count
Write-Host "Hosted VMs :", $HostedVMs.Count
if ($VMHosts.Count -ne 0)
{
Write-Host "VMs per Host :", ($HostedVMs.Count / $VMHosts.Count)
}
####################################################################
# Summary of Virtual Machine Hosts
####################################################################
$VMHosts = @(Get-VMHost)
Write-Host "`nVIRTUAL MACHINE HOSTS" -ForegroundColor Yellow
Write-Host "Total Hosts :", $VMHosts.Count
Write-Host "Hosts Not Responding :", @($VMHosts | where {$_.Status -eq "NotResponding"}).Count
Write-Host "Hosts Needing Agent Update :", @($VMHosts | where {$_.Agent.VersionState -eq "NeedsUpdate"}).Count
Write-Host "Hosts Needing Virtual Server Update :", @($VMHosts | where {$_.VirtualServerVersionState -eq "NeedsUpdate"}).Count
Write-Host "Hosts in Maintenance :", @($VMHosts | where {$_.MaintenanceHost -eq $true}).Count
Write-Host "Hosts on Perimeter Network :", @($VMHosts | where {$_.PerimeterNetworkHost -eq $true}).Count
####################################################################
# Summary of Virtual Machines
####################################################################
$VMs = @(Get-VM)
Write-Host "`nVIRTUAL MACHINES" -ForegroundColor Yellow
Write-Host "Total VMs :", $VMs.Count
Write-Host "Hosted VMs :", @($VMs | where {$_.Status -ne "Stored"}).Count
Write-Host "Stored VMs :", @($VMs | where {$_.Status -eq "Stored"}).Count
Write-Host "Running VMs :", @($VMs | where {$_.Status -eq "Running"}).Count
Write-Host "Self-Service VMs :", @($VMs | where {$_.SelfServicePolicy -ne $null}).Count
Write-Host "VMs without VMAdditions :", @($VMs | where {$_.HasVMAdditions -eq $false}).Count
####################################################################
# Summary of Self-Service
####################################################################
$SelfServicePolicies = @(Get-SelfServicePolicy)
$VMs = @(Get-VM)
Write-Host "`nSELF-SERVICE" -ForegroundColor Yellow
Write-Host "Self Service Policies :", $SelfServicePolicies.Count
Write-Host "Total Self-Service VMs :", @($VMs | where {$_.SelfServicePolicy -ne $null}).Count
Write-Host "Hosted Self-Service VMs :", @($VMs | where {$_.SelfServicePolicy -ne $null} | where {$_.Status -ne "Stored"}).Count
Write-Host "Stored Self-Service VMs :", @($VMs | where {$_.SelfServicePolicy -ne $null} | where {$_.Status -eq "Stored"}).Count
####################################################################
# Summary of Library Servers
####################################################################
$LibraryServers = @(Get-LibraryServer)
$VMs = @(Get-VM)
Write-Host "`nLIBRARY SERVERS" -ForegroundColor Yellow
Write-Host "Library Servers :", $LibraryServers.Count
Write-Host "Stored VMs :", ($VMs | where {$_.Status -eq "Stored"}).Count
####################################################################
# Summary of Virtual Machine Host Groups
####################################################################
$VMHostGroups = @(Get-VMHostGroup)
$VMs = @(Get-VM)
Write-Host "`nVIRTUAL MACHINE HOST GROUPS" -ForegroundColor Yellow
foreach ($VMHostGroup in $VMHostGroups)
{
$VMHostCount = $VMHostGroup.Hosts.Count
$VMCount = @($VMs | where {$VMHostGroup.Hosts -contains $_.VMHost}).Count
$RunningVMCount = @($VMs | where {$VMHostGroup.Hosts -contains $_.VMHost} | where {$_.Status -eq "Running"}).Count
$SelfServiceVMCount = @($VMs | where {$VMHostGroup.Hosts -contains $_.VMHost} | where {$_.SelfServicePolicy -ne $null}).Count
Write-Host "Host Group :", $VMHostGroup.Name
Write-Host "Number of Hosts :", $VMHostCount
if ($VMHostCount -ne 0)
{
Write-Host "Number of VMS :", $VMCount
Write-Host "Running VMs :", $RunningVMCount
Write-Host "Self-Service VMs :", $SelfServiceVMCount
Write-Host "VMs per Host :", ($VMCount / $VMHostCount)
Write-Host "Running VMs per Host :", ($RunningVMCount / $VMHostCount)
Write-Host "Self-Service VMs per Host :", ($SelfServiceVMCount / $VMHostCount)
}
Write-Host
}
Appendix A: About Windows PowerShell for Virtual Machine Manager
You can use the Windows PowerShell - Virtual Machine Manager command shell to perform all administrative functions in Virtual Machine Manager either interactively from the command line or through the use of scripts. For those not yet familiar with either Windows PowerShell or Virtual Machine Manager, this appendix explains the relationship between the two technologies.
How Virtual Machine Manager Uses Windows PowerShell
Windows PowerShell and Virtual Machine Manager each provide commands (called cmdlets) that you can use separately to perform simple administrative tasks or together with other cmdlets or command-line elements to perform complex tasks.
The Virtual Machine Manager command shell includes all of the standard Windows PowerShell cmdlets and also provides a comprehensive set of cmdlets that are designed specifically for use with Virtual Machine Manager. You can use these cmdlets to manage all functions in a Virtual Machine Manager environment, including the following tasks:
ï‚· Adding and working with virtual machine hosts and host groups
ï‚· Adding the Virtual Machine Manager library and maintaining the resources that it stores
ï‚· Creating and working with virtual machines that are deployed on a host or stored in the library
ï‚· Managing the virtual machine environment
ï‚· Creating virtual machine checkpoints
ï‚· Backing up the Virtual Machine Manager database
ï‚· Administering the virtual machine self-service feature
Windows PowerShell and Virtual Machine Manager differentiate between commands and cmdlets as follows:
ï‚· Cmdlet. A cmdlet is a single-feature command that is used to interact with any managed application, including Virtual Machine Manager, and the operating system. A cmdlet is typically formatted as a verb-noun pair separated by a dash (such as Get-VirtualNetwork). The verb acts on a Windows PowerShell object (the noun).
Most cmdlets are simple but designed to work in combination with other cmdlets. For example, the “Get” cmdlets only retrieve data and the “Set” cmdlets only specify or change data.
Example of a Virtual Machine Manager cmdlet:
Get-VMCheckPoint
ï‚· Command. A command might or might not include one or more cmdlets. Examples of commands that do not include cmdlets are 2+2 or the assignment of a value or an array of values to a variable, such as $IntegerArray = @(0,1,2,3,4,5,6,7,8,9). However, assigning a value to a variable often does include the use of a cmdlet, such as $Credential = Get-Credential, which prompts you for Active Directory credentials (<DomainName>\<UserName> and password) and then stores those credentials in the variable $Credential. A command can use a pipeline operator (|) to pass the output of one cmdlet to another cmdlet as input.
Example of a Virtual Machine Manager command that uses the pipeline operator:
Get-VMCheckpoint -MostRecent | where { $_.VM -eq "VM01" } | Restore-VMCheckpoint
Customers who have installed Virtual Machine Manager can access both standard Windows PowerShell cmdlets and Virtual Machine Manager cmdlets at the Virtual Machine Manager command-line interface. Windows PowerShell command-line Help for the standard Windows PowerShell cmdlets is provided with Windows; command-line Help for Virtual Machine Manager cmdlets is provided with the Virtual Machine Manager product.
How a Snap-in Provides Virtual Machine Manager Cmdlets
Windows PowerShell is installed with a set of built-in snap-ins. These Windows PowerShell snap-ins contain:
ï‚· Providers. The standard Windows PowerShell providers provide access to various data stores in a format that is modeled on the file system interface in Windows.
ï‚· Cmdlets. The standard Windows PowerShell cmdlets are available for use with any server product that supports Windows PowerShell, including Virtual Machine Manager.
For example, the Microsoft.PowerShell.Core snap-in includes the FileSystem, Registry, Alias, Environment, Function, and Variable providers and also includes basic cmdlets such as Get-Help, Get-Command, and Get-History.
Like other Microsoft server products, such as Microsoft Exchange Server or Microsoft System Center Operations Manager 2007, Virtual Machine Manager extends the standard functionality of Windows PowerShell by providing its own Windows PowerShell snap-in. The Virtual Machine Manager snap-in for Windows PowerShell does not include a separate Windows PowerShell provider for Virtual Machine Manager, but it does provide a set of Virtual Machine Manager cmdlets. You can use these cmdlets with, or as an alternative to, the Virtual Machine Manager Administrator Console to manage your servers and virtual machines.
To see the complete list of Windows PowerShell snap-ins
1. On a Virtual Machine Manager server on which the Administrator Console for Virtual Machine Manager is installed, click Start, point to All Programs, point to Microsoft System Center Virtual Machine Manager 2007, and then click Windows PowerShell - Virtual Machine Manager to open the command shell. 2. At the command prompt, type the following command to list the Virtual Machine Manager cmdlets: Get-PSSnapin 3. Review the command output and confirm that the list includes an entry called VirtualMachineManagerSnapin |
To list the Virtual Machine Manager cmdlets
1. At the command prompt, type the following command: Get-Command -PSSnapin VirtualMachineManagerSnapin 2. Confirm that the output lists the Virtual Machine Manager cmdlets. The first cmdlet listed is Add-LibraryServer and the last cmdlet is Update-VMMManagedComputer. |
How the Administrator Console Uses Virtual Machine Manager Cmdlets
The Virtual Machine Manager Administrator Console is built on Windows PowerShell. Most server administrators do not need an in-depth understanding, at the programmatic level, of the interaction between the Administrator Console and Windows PowerShell. However, the following synopsis of the standard call sequence for any hypothetical Administrator Console operation illustrates the integration of Windows PowerShell and the Administrator Console:
1. The Administrator Console makes a call to a Windows PowerShell cmdlet.
2. The Windows PowerShell cmdlet makes a Windows Communication Foundation call to the Virtual Machine Manager server service.
3. Virtual Machine Manager initiates a job if the operation changes state or is long-running and, therefore, needs to be audited or monitored asynchronously.
4. Virtual Machine Manager makes SQL calls, as necessary, to read and update the Virtual Machine Manager database.
5. Virtual Machine Manager makes Windows Remote Management (WinRM) calls, as necessary, to access remote hosts on which virtual machines are deployed or to access remote library servers on which Virtual Machine Manager library resources are stored.
6. WinRM calls, in turn, access Windows Management Instrumentation (WMI) methods on Virtual Machine Manager hosts or library servers. These WMI methods ship either in the operating system or as part of the Virtual Machine Manager agent service.
7. Some of these WMI methods, in turn, call the Virtual Server component object model application programming interface (COM API).
All operations that you perform by using the Administrator Console in Virtual Machine Manager are actually performing these tasks.
How Objects Represent All Entities in Virtual Machine Manager
All entities in a Virtual Machine Manager environment are represented as an object. This section provides a brief introduction to the use of objects in Windows PowerShell in the context of Virtual Machine Manager.
Windows PowerShell, although it is based on object-oriented programming and Microsoft .NET Framework classes, does not require server administrators to gain an exhaustive knowledge of these topics. On the contrary, Windows PowerShell is designed to enable server administrators to learn quickly how to manipulate objects either interactively at the command-line or through scripting.
How Managing Objects Is More Efficient Than Text-Based Processing
One of the most important features to understand about objects is how the use of objects by Windows PowerShell differs from the text-based processing that is characteristic of many earlier command shells. Traditional command shells that use text-based processing require a variety of text processing utilities in order to function.
By contrast, Windows PowerShell transfers data between its cmdlets as structured objects rather than as text, which means that each Windows PowerShell cmdlet can interpret and act on any object that is passed to it. The cmdlet that receives the object can act directly on that object and its properties without requiring any conversion or manipulation, as is the case for text-based processing.
How to Access an Object
Each of the objects that Windows PowerShell for Virtual Machine Manager uses is an instance of a .NET Framework class, which consists of data and operations that are associated with that data. An object is made up of three kinds of data:
ï‚· Type. The type of the object indicates what kind of object it is. For example, the type for a Virtual Machine Manager library server is:
TypeName: Microsoft.SystemCenter.VirtualMachineManager.LibraryServer
Properties. The properties of the object are its characteristics. After you connect to the Virtual Machine Manager database, when you run the Get-<Object> cmdlet for any Virtual Machine Manager object (such as Get-VMHost, Get-VirtualNetwork, Get-VirtualDVDDrive, and so on), you see a list of information about the state of each property for that object.
ï‚· Methods. The methods of the object are the actions that you can perform on the entity (such as a server or virtual machine) that the object represents.
When you call a cmdlet by typing the cmdlet name at the command line, the command shell returns the specified object. In a single command line, you can use one or more pipeline operators (|) to pass an object from one cmdlet to another. You specify properties and methods of the object by name, rather than by having to calculate the position of the data in output that is formatted as text.
All objects of the same type, such as a specific type of file or a specific type of server, share the same properties and methods, but each instance of an object can have different values for its properties. For example, all Virtual Machine Manager library servers are the same type of object, but, typically, you define a different Name and Description property for each library server object, whereas multiple servers might have the same value for the DomainName property.
Differentiating Between an Object and What It Represents
An object is not the same as the entity that the object represents. For example, a library server object is not the library server itself. Rather, it represents the physical file server that is configured as a Virtual Machine Manager library server so that you can use cmdlets to perform operations on that server. You might use the Add-LibraryServer cmdlet to add a new library server object to the Virtual Machine Manager database, or you might use the Get-LibraryServer cmdlet to retrieve the object that represents an existing library server and view its properties.
A Windows PowerShell array, including a Virtual Machine Manager array, is an array of objects. You might, for example, create an array that stores the object that represents each virtual machine that is currently turned off and then pass all of these virtual machine objects to a cmdlet that starts each virtual machine in the array.
Typically, an array contains objects of the same type. However, an untyped array in Windows PowerShell can contain different types of .NET Framework objects in each element of the array.
Viewing an Object
You can use the standard Windows PowerShell cmdlet, Get-Member, to view the properties and methods of any object, as shown in the following example.
To display the type, methods, and properties for the Virtual Machine Manager server object
1. On a Virtual Machine Manager server on which the Administrator Console for Virtual Machine Manager is installed, click Start, point to All Programs, point to Microsoft System Center Virtual Machine Manager 2007, and then click Windows PowerShell - Virtual Machine Manager to open the command shell. 2. At the command prompt, type the following two commands: a. $VMMServer = Get-VMMServer -Computername “<YourVMMServerName>.<YourDomainName>.com” b. $VMMServer | Get-Member 3. Confirm that the command output displays the object type and lists a set of methods and a set of properties for the server object. In the following example, the object type appears at the top of the output in the following format: TypeName: Microsoft.SystemCenter.VirtualMachineManager. Remoting.ServerConnection In the following example, following the TypeName header, the output lists the name and definition for all methods and properties that are associated with the Virtual Machine Manager server object. |
How Virtual Machine Manager Cmdlets Work with Objects
You can use Virtual Machine Manager cmdlets to manage all Virtual Machine Manager objects at the command line. These objects are stored in a SQL Server database called the Virtual Machine Manager database. The database is stored on the Virtual Machine Manager server itself or on a remote SQL server that is associated with the Virtual Machine Manager server. Virtual Machine Manager supports SQL Server 2005 and Microsoft SQL Server 2005 Express Edition SP1.
Examples of Virtual Machine Manager objects include:
ï‚· Computers. Objects that represent each type of physical or virtual computer in a Virtual Machine Manager environment are stored in the Virtual Machine Manager database. These servers include the Virtual Machine Manager server itself, servers that act as hosts for virtual machines, servers that act as libraries to store resources, Web servers that act as Self-Service Portals (for users who allowed to create or manage their own virtual machines, or both), and virtual machines that are either deployed on a host or stored in the library.
ï‚· Resources. Objects that represent library resources (such as library shares, virtual machine templates, ISO images, scripts, and so on) that are stored in the library catalog in the Virtual Machine Manager database. Files that these library objects represent are stored as specific file types on the physical library server.
ï‚· Components of a virtual machine. Objects that represent parts of a virtual machine (such as virtual floppy drives, virtual network adapters, virtual SCSI adapters, or virtual COM ports) can be stored on a virtual machine, on a template, or on a hardware profile.
The Virtual Machine Manager cmdlets typically use standard Windows PowerShell verb names for similar actions performed on specific objects. For example:
ï‚· New-<Object> cmdlets. Used to create new objects (such as virtual machines, virtual network adapters, templates, or self-service policies) and store them in the Virtual Machine Manager database.
ï‚· Add-<Object> cmdlets. Used to add a object for something that already exists (such as a library server, a library share, a host server, a host network adapter, or a virtual hard disk) to the Virtual Machine Manager database. Other objects are added to the database automatically.
ï‚· Get-<Object> cmdlets. Used to retrieve the object that represents a Virtual Machine Manager entity (such as a host, host group, virtual machine, template, script, job, self-service policy, or any other Virtual Machine Manager object) from the Virtual Machine Manager database. You can then review the characteristics of that retrieved object or use other Virtual Machine Manager cmdlets to act on that object.
ï‚· Set-<Object> cmdlets. Used to specify or change data (properties) associated with an object.
ï‚· Remove-<Object> cmdlets. Used to remove an object from the Virtual Machine Manager database.
The preceding list is not the complete list of verbs for Virtual Machine Manager cmdlets, but each of these verbs is used for all or most objects in both standard Windows PowerShell and in Virtual Machine Manager.
How Virtual Machine Manager Updates Objects Stored in the Library
The following scenario outlines a simple but typical administrative situation. In the following scenario, you have a large Virtual Machine Manager library that is distributed across multiple physical machines, and, therefore, library resources might be stored as files on any of several library servers. However, the objects that represent each library server (and the objects that represent every resource stored on each of those library servers) are all stored in the Virtual Machine Manager database that is managed by the Virtual Machine Manager server service.
ï‚· A file that you use in your Virtual Machine Manager environment called "SysPrepAnswerFile" is stored in NetworkShareA on the physical library server called LibServ01.
ï‚· You use a file system tool (such as Windows Explorer) to move SysPrepAnswerFile to NetworkShareB on LibServ02.
ï‚· Through one of the following methods, Virtual Machine Manager discovers that you moved SysPrepAnswerFile to a different folder on another server:
ï‚· By default, the Virtual Machine Manager library refresher feature is enabled. The library refresher discovers new or moved objects that are stored in shares on library servers at regular intervals (by default, once every hour) and updates the Virtual Machine Manager database accordingly.
ï‚· Alternatively, you can run the Refresh-LibraryShare cmdlet at any time to update immediately the state and metadata of all Virtual Machine Manager library objects stored in the specified share or shares.
How Virtual Machine Manager "Live" Objects Work
Virtual Machine Manager objects differ from standard Windows PowerShell objects because all Virtual Machine Manager objects are "live" and are thus are kept synchronized with each other. Standard Windows PowerShell objects typically are not synchronized.
For example, if you type the series of commands shown in the following procedure at the Windows PowerShell command line, the final result is that the contents of $StandardPSObject1 and the contents of $StandardPSObject2 are not the same.
To verify that Windows PowerShell objects are not synchronized
1. On any computer on which Windows PowerShell is installed, click Start, point to All Programs, point to Windows PowerShell 1.0, and then click Windows PowerShell to open the command shell.
The command shell that you open is the standard version of Windows PowerShell and does not include the Virtual Machine Manager cmdlets. 2. Type the following series of commands at the command prompt, and then view the results: a. $StandardPSObject1 = "abc" b. $StandardPSObject2 = $StandardPSObject1 c. $StandardPSObject1 = "123" d. $StandardPSObject1 e. $StandardPSObject2 3. View the output to confirm that the contents of $StandardPSObject1 is 123, but the contents of $StandardPSObject2 is abc. Standard Windows PowerShell does not synchronize objects. |
However, if you type the series of commands shown in the following procedure at the command line in the Virtual Machine Manager command shell, the final result is that both Virtual Machine Manager objects contain the same information.
To verify that Virtual Machine Manager objects are synchronized
1. On a Virtual Machine Manager server on which the Administrator Console for Virtual Machine Manager is installed, click Start, point to All Programs, point to Microsoft System Center Virtual Machine Manager 2007, and then click Windows PowerShell - Virtual Machine Manager to open the command shell.
The following example assumes that you have a Virtual Machine Manager server named VMMServer1 and a file server named LibServ01 and that both servers are located in the Contoso.com domain. It also assumes that you have an ISO image named VMAdditions. 2. Type the following series of commands at the command prompt, and then view the results: a. $VmmIsoObject1 = Get-ISO -VMMServer VMMServer1.Contoso.com | where { $_.Name -eq "VMAdditions" -and $_.LibraryServer.Name -eq "LibServ01.Contoso.com" } b. $VmmIsoObject2 = Get-ISO -VMMServer VMMServer1.Contoso.com | where { $_.Name -eq "VMAdditions" -and $_.LibraryServer.Name -eq "LibServ01.Contoso.com" } c. Set-ISO -ISO $VmmIsoObject2 -Name “VMAdditions-RTM” d. $VmmIsoObject1 | format-list -property Name e. $VmmIsoObject2 | format-list -property Name 3. Confirm that the name displayed for both $VmmIsoObject1 and $VmmIsoObject2 is VMAdditions-RTM. In the Windows PowerShell - Virtual Machine Manager command shell, objects are synchronized. |
The commands in the preceding example perform the following tasks:
ï‚· The first command retrieves from the library catalog in the Virtual Machine Manager database the object that represents the ISO file named VMAdditions on library server LibServ01. The command stores the ISO object in variable $VmmIsoObject1.
ï‚· The second command retrieves the same object and stores it in variable $VmmIsoObject2. Retrieving and storing the object might be done, for example, by a different server administrator working on a different computer.
ï‚· The third command changes the name of the object stored in $VmmIsoObject2 to VMAdditions-RTM.
ï‚· The last two commands display the name property of the objects stored in variables $VmmIsoObject1 and $VmmIsoObject2. Because all Virtual Machine Manager objects are "live" objects, they are synchronized, so, as the output shows, the name of the object in each variable has been changed to VMAdditions-RTM.
Appendix B: Introductory Command-Line Tutorial
You can use the standard Microsoft Windows PowerShell cmdlets with the cmdlets that are provided by Virtual Machine Manager for interactive system administration and for scripting administrative tasks. Standard Windows PowerShell cmdlets and Virtual Machine Manager cmdlets are available on any computer on which the Virtual Machine Manager Administrator Console is installed.
The examples in this tutorial assume that you have installed the Administrator Console and the Windows PowerShell - Virtual Machine Manager command shell on your Virtual Machine Manager server.
How to Find the Virtual Machine Manager Command Shell
You can open the Windows PowerShell - Virtual Machine Manager command shell by using either of the methods shown in the following two procedures.
To open the Virtual Machine Manager command shell from the All Programs menu
1. On a Virtual Machine Manager server on which the Administrator Console for Virtual Machine Manager is installed, click Start, point to All Programs, point to Microsoft System Center Virtual Machine Manager 2007, and then click Windows PowerShell - Virtual Machine Manager. 2. When the command shell opens, confirm that the Virtual Machine Manager snap-in has loaded by typing the following command at the command line: Get-Help Get-VMMServer If a Help topic about the Virtual Machine Manager cmdlet Get-VMMServer is displayed, the Virtual Machine Manager snap-in is loaded. You can substitute any Virtual Machine Manager cmdlet for Get-VMMServer. |
To open the Virtual Machine Manager command shell from the Windows PowerShell command shell
1. On a Virtual Machine Manager server on which the Administrator Console for Virtual Machine Manager is installed, click Start, point to All Programs, point to Windows PowerShell 1.0, and then click Windows PowerShell. The menu from which you just opened Windows PowerShell also includes the following documentation about Windows PowerShell: ï‚· Getting Started ï‚· Quick Reference ï‚· Release Notes ï‚· User Guide For a comprehensive introduction to Windows PowerShell, review each of the documents. 2. When the Windows PowerShell command shell opens, open the Windows PowerShell - Virtual Machine Manager version of the command shell and load the Virtual Machine Manager cmdlets, by typing: Add-PSSnapin VirtualMachineManagerSnapin 3. When the command shell opens, confirm that the Virtual Machine Manager snap-in has loaded by typing the following command at the command line: Get-Help New-VM If a Help topic about the Virtual Machine Manager cmdlet New-VM is displayed, the Virtual Machine Manager snap-in is loaded. You can substitute any Virtual Machine Manager cmdlet for New-VM. |
You can open multiple command shells at the same time. For example, you might want to read Help topic examples in one window and try running the examples in another window.
How to Use Basic Windows PowerShell Cmdlets
You can use standard Windows PowerShell cmdlets with Virtual Machine Manager cmdlets. To get started, two standard Windows PowerShell cmdlets that you need to be familiar with are Get-Help and Get-Command.
Note
Examples use uppercase letters for readability, but Windows PowerShell is not case sensitive.
To display basic information provided by Get-Help and Get-Command
1. In the Windows PowerShell - Virtual Machine Manager command-shell window, type the following command and review its output: Get-Help Get-Help Typing Get-Help <AnyCmdlet-Name> displays Help information about the second cmdlet. 2. In another Windows PowerShell - Virtual Machine Manager command-shell window, type the following command and review its output: Get-Command The Get-Command cmdlet lists all Windows PowerShell cmdlets, including all Virtual Machine Manager cmdlets, if you are in the Windows PowerShell - Virtual Machine Manager command shell, as these examples assume. Later, you will learn how to list only Virtual Machine Manager cmdlets. |
To clear the screen
ï‚· Type the following command to clear the screen: Clear-Host Alternatively, you can use one of the aliases for this cmdlet, Clear or Cls. |
To display detailed information about Get-Help and Get-Command
1. In one command-shell window, type the following command and review its output: Get-Help Get-Help -detailed 2. In another command-shell window, type the following command and review its output: Get-Help Get-Command -detailed When you include the -detailed parameter, the Help includes a description for each parameter but excludes other parameter details. |
To display full information about Get-Help and Get-Command
1. In one command-shell window, type the following command and review its output: Get-Help Get-Help -full 2. In another command-shell window, type the following command and review its output: Get-Help Get-Command -full When you include the -full parameter, the Help includes all available information about each parameter. |
To display only the examples for Get-Help and Get-Command
1. In one command-shell window, type the following command and review its output: Get-Help Get-Help -example 2. In another command-shell window, type the following command and review its output: Get-Help Get-Command -example When you include the -example parameter, the Help displays only the Synopsis and the set of examples for that cmdlet. |
To display a Help topic one screen at a time
1. Type the following command to see the Help topic for Get-Command or for any cmdlet, one screen at a time: Help Get-Command -full 2. Press the Spacebar to display the next screen. If you press ENTER, only one additional line at a time is displayed. |
How to Get Information About Virtual Machine Manager Cmdlets
This section shows you how to get basic information about Virtual Machine Manager cmdlets.
To list all Windows PowerShell snap-ins
1. Type the following command and review its output: Get-PSSnapin 2. Confirm that you see the list of standard Windows PowerShell snap-ins (such as Microsoft.PowerShell.Core) followed by the Virtual Machine Manager snap-in. |
To list only cmdlets included in the Virtual Machine Manager snap-in
1. Type the following command and review its output: Get-Command -PSSnapin VirtualMachineManagerSnapin 2. Confirm that you see a list of cmdlets that includes Virtual Machine Manager cmdlets, such as Add-VMHost, Get-VM, or Update-VMMManagedComputer. |
To list only Virtual Machine Manager cmdlets in a different format
ï‚· Type the following command and review its output: Get-Command -PSSnapin VirtualMachineManagerSnapin | Sort-Object Noun | Format-Table -Group Noun If you want to learn more about the standard Windows PowerShell cmdlets Sort-Object or Format-Table, type Get-Help Sort-Object and type Get-Help Format-Table. |
To discover where the shell finds different types of cmdlets
1. In one command-shell window, type the following command and review its output: Get-Command Get-VMMServer | Format-List -property implementingtype,pssnapin If you want to learn more about the standard Windows PowerShell cmdlet Format-List, type Get-Help Format-List. 2. In another command-shell window, type the following command and review its output: Get-Command Get-Help | Format-List -property implementingtype,pssnapin 3. Compare the output of both commands and confirm that you can discover the origin of each cmdlet by looking at the output: ï‚· For Get-VMMServer, confirm that the output is: ImplementingType : Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.ConnectServerCmdlet PSSnapIn : VirtualMachineManagerSnapIn ï‚· For Get-Help, confirm that the output is: ImplementingType : Microsoft.PowerShell.Commands.GetHelpCommand PSSnapIn : Microsoft.PowerShell.Core |
To display information about the command that connects to the Virtual Machine Manager database
1. Type the following command and review its output: Get-Help Get-VMMServer -detailed 2. Review the DETAILED DESCRIPTION and the examples. Most multiple-line interactive commands that are used to administer Virtual Machine Manager start by using the Get-VMMServer cmdlet to connect to Virtual Machine Manager: Get-VMMServer -ComputerName YourVMMServerName.YourDomainName.com |
To display only the syntax for Get-VMMServer
ï‚· Type the following command and review its output: Get-Command Get-VMMServer -Syntax This method of displaying only the syntax is an alternative to using Get-Help Get-VMMServer, which displays other information in addition to the syntax. |
To view Help for a cmdlet that has more than one parameter set
1. Type the following command and review its output: Get-Help Add-VMHost 2. Confirm that the output has the following two sets of parameters available for use with the Add-VMHost cmdlet, depending on whether you are adding the host to your primary network or to a perimeter network: Add-VMHost -Credential <Credential> [-EncryptionKey <String>] [-Reassociate] [-RunAsynchronously <Boolean>] [-VMMServer] [-VMRCEnabled] [-VMRCTimeoutEnabled] [-VMRCTimeoutMinutes] [<CommonParameters>] Add-VMHost -PerimeterNetworkHost -SecurityFile <String> [-EncryptionKey <String>] [-Reassociate] [-RunAsynchronously <Boolean>] [-VMMServer] [-VMRCEnabled] [-VMRCTimeoutEnabled] [-VMRCTimeoutMinutes] [<CommonParameters>] |
To display the description of a specific parameter
1. Look at the first parameter set for Add-VMHost (in the preceding example procedure), type the following command, and then review its output: Get-Help Add-VMHost -parameter Reassociate 2. Look at the second parameter set for Add-VMHost (in the preceding example procedure), type the following command, and then review its output: Get-Help Add-VMHost -parameter PerimeterNetworkHost 3. Look at either parameter set for Add-VMHost (in the preceding example procedure), type the following command, and then review its output: Get-Help about_CommonParameters You must use a different command to display information about the parameter called <CommonParameters> because this set of parameters is shared by most cmdlets (both standard Windows PowerShell cmdlets and Virtual Machine Manager cmdlets). |
To see how Get-Help and Get-Command handle wildcards
1. In one command-shell window, type the following command and review its output: Get-Help *virtualcom* 2. In another command-shell window, type the following command and review its output: Get-Command *virtualcom* 3. Confirm that the output for step 1 shows the first part of the Synopsis for each cmdlet that contains the string "virtualcom" in its name, and the output for step 2 shows the first part of the syntax for each cmdlet that contains the string "virtualcom" in its name. |
To view a limited set of properties for cmdlets by using wildcards
1. In one command-shell window, type the following command and review its output: Get-Help *virtualcom* | Format-List -property Name, Synopsis 2. In another command-shell window, type the following command and review its output: Get-Command *virtualcom* | Format-List -property Name, ImplementingType |
How to Get Information About Virtual Machine Manager
When you open a Windows PowerShell - Virtual Machine Manager command-shell window, you can display Help about Virtual Machine Manager cmdlets at any time (as shown in the preceding section), but you cannot actually use any of the Virtual Machine Manager cmdlets until after you connect to the Virtual Machine Manager server. Connecting to the Virtual Machine Manager server retrieves the server object from the Virtual Machine Manager database and gives you access to all other objects in the SQL Server database, which stores all Virtual Machine Manager objects for as long as the connection lasts or until you close the command-shell window.
Important
The examples in this section assume that you have access to a Virtual Machine Manager server on which the Administrator Console is installed and that at least one virtual machine host, library server, and virtual machine exist.
To connect to the Virtual Machine Manager server
ï‚· Type the following command, substituting your own server and domain names, and review the output: Get-VMMServer -Computername “<YourVMMServerName>.<YourDomainName>.com” When the command is completed successfully: ï‚· Server object is returned. The shell displays information about the properties of the Virtual Machine Manager server object. ï‚· Database is available. You are connected to the Virtual Machine Manager database that is provided by the Virtual Machine Manager server. In the rest of this tutorial, many of the commands require that you be connected to the Virtual Machine Manager database. If you find that a command does not work, try running the command in this procedure again. If you encounter problems, trying opening the Services tool in Administrative Tools and restart the Virtual Machine Manager service (or type Get-Help Restart-Service -detailed to read the standard Windows PowerShell Help topic that tells you how to restart a service at the command line). |
To connect to Virtual Machine Manager if it is installed on the local host
ï‚· Type the following command and review its output: Get-VMMServer -Computername localhost If you are working on the server on which Virtual Machine Manager is installed (rather than accessing it remotely), you can substitute "localhost" for the fully qualified domain name (FQDN). |
To display information only about specific properties of the VMMServer object
ï‚· Type the following command and review its output: Get-VMMServer -Computername “<YourVMMServerName>.<YourDomainName>.com” | Format-List -property Name, FullyQualifiedDomainName, PlacementGoal, MemoryPriority, DiskIOPriority, CPUPriority, NetworkPriority |
To display information about specific properties of host servers and library servers, grouped by name
1. Type the following command and review its output: Get-VMMManagedComputer | Format-List -property Name,Role,State -GroupBy Role 2. Type the following command and review its output: Get-VMMManagedComputer | Format-Table -property Name,Role,State, -GroupBy Role |
To display all properties and methods available for the Virtual Machine Manager server object
1. Type the following command to connect to the Virtual Machine Manager server and store the server object in variable $VMMServer: $VMMServer = Get-VMMServer -Computername "<YourVMMServerName>.<YourDomainName>.com" 2. Type the following command to display the contents of $VMMServer to confirm that this variable contains the server object: $VMMServer 3. Type the following command to pass the contents of $VMMServer to the standard Windows PowerShell cmdlet Get-Member, which displays the properties and methods that are associated with this server object: $VMMServer | Get-Member The properties of the object are its characteristics. The methods of the object are the actions that you can perform on the entity (such as a server or virtual machine) that this object represents. |
To list cmdlets associated with commonly used Virtual Machine Manager verbs
ï‚· Type one or more of the following series of commands: Get-Command -PSSnapin VirtualMachineManagerSnapin -Verb New Get-Command -PSSnapin VirtualMachineManagerSnapin -Verb Add Get-Command -PSSnapin VirtualMachineManagerSnapin -Verb Get Get-Command -PSSnapin VirtualMachineManagerSnapin -Verb Set Get-Command -PSSnapin VirtualMachineManagerSnapin -Verb Remove After you type the first command, use the UP arrow to repeat the command, and (instead of pressing ENTER), backspace to delete New, and then type Add. |
To list cmdlets associated with commonly used Virtual Machine Manager nouns
ï‚· Type one or more of the following series of commands: Get-Command -Noun VMMServer Get-Command -Noun VMHost Get-Command -Noun MachineConfig Get-Command -Noun LibraryServer Get-Command -Noun LibraryShare Get-Command -Noun VM Get-Command -Noun HardwareProfile Get-Command -Noun GuestOSProfile Get-Command -Noun Template Get-Command -Noun VirtualNetwork Get-Command -Noun VMHostNetworkAdapter Get-Command -Noun VirtualNetworkAdapter Get-Command -Noun SelfServiceWebServer Get-Command -Noun SelfServicePolicy In this example (in contrast to the preceding example), you can omit typing PSSnapin VirtualMachineManagerSnapin because all the nouns are unique to Virtual Machine Manager. |
How to Use Virtual Machine Manager Help Topics
One way to start using Virtual Machine Manager cmdlets is by experimenting with the “Get” cmdlets. These cmdlets retrieve Virtual Machine Manager objects from the Virtual Machine Manager database that is managed by the Virtual Machine Manager service. You can display information about an object, or you can store an object in a variable to be used by a subsequent cmdlet.
To list only the Virtual Machine Manager cmdlets that begin with “Get”
ï‚· Type the following command and review its output: Get-Command -PSSnapin VirtualMachineManagerSnapin -Verb Get |
To display examples for the following key Virtual Machine Manager “Get” cmdlets
ï‚· Type one or more of the following series of commands: Get-Help Get-VMMServer -example Get-Help Get-VMHost -example Get-Help Get-LibraryServer -example Get-Help Get-VMMManagedComputer -example Get-Help Get-VM -example Get-Help Get-Template -example Get-Help Get-HardwareProfile -example Get-Help Get-GuestOSProfile -example As you display the examples for a specific cmdlet in one command-shell window, try running one or more of the examples in another command-shell window. After you are comfortable using the “Get” cmdlets, you might want to display the examples for the “New,” “Add,” “Set,” “Remove,” and other cmdlets and use or adapt those examples as you experiment with your own Virtual Machine Manager environment. |
How to Search or Save Cmdlet Help Topics
This section shows you how to search cmdlet Help topics from the command line and how to save one or all Help topics to a text file.
To search the main Windows PowerShell cmdlet Help files
1. Type the following command to change to the directory where the standard Windows PowerShell Help files are stored: Set-Location $pshome
Alternatively, you can use the alias for Set-Location: cd $pshome 2. Confirm that the new path in the command prompt changes to: PS <C>:\WINDOWS\system32\WindowsPowerShell\v1.0> where "<C>" is the drive on which the Windows operating system is installed on this computer. 3. Type the following command to search the standard Windows PowerShell Help topics for the string "credential parameter" (or specify a different string): findstr /I /C:”credential parameter" *.xml, *.txt
For information about when single and double quotes are interchangeable in Windows PowerShell—and when they are not—type at the command prompt: Get-Help about_quoting_rules |
To search the Virtual Machine Manager cmdlet Help files
1. Type the following command to change to the directory where the Virtual Machine Manager Help files are stored: cd <C>:\'Program Files'\'Microsoft System Center Virtual Machine Manager 2007'\bin Replace "<C>" with the letter of the drive on which your Virtual Machine Manager files are installed, and confirm that the command prompt changes to the Virtual Machine Manager bin directory. 2. Type the following command to search the Virtual Machine Manager Help topics for the string "library server" (or specify a different string): findstr /I /C:”library server” *.xml, *.txt |
To display information about the findstr command
ï‚· Type the following command and review its output: findstr /? The findstr command is a Cmd.exe command. Windows PowerShell supports many legacy Cmd.exe and UNIX commands. |
To return to your home directory
ï‚· Type the following command to return to your home directory: cd $home
By default, your home directory is: <C>:\Documents and Settings\YourAlias> |
To save a single Help topic to a text file
1. Type the following command to change to your My Documents folder: cd 'My Documents' 2. Type the following commands to save the contents of a single Help topic (in this example, the Help topics for Get-VMHostRating and Remove-VirtualNetworkAdapter) to a text file: Get-Help Get-VMHostRating -detailed | Out-File Get-VMHostRating.txt Alternatively, you can use the redirection operator: Get-Help Remove-VirtualNetworkAdapter -detailed > Get-VMHostRating.txt 3. Open Windows Explorer and then open Get-VMHostRating.txt in your My Documents folder to confirm that the text file contains the Help topic for Get-VMHostRating. |
To save all Help topics for every Virtual Machine Manager cmdlet to a text file
1. Type the following command and review its output: Get-Command -PSSnapin VirtualMachineManagerSnapin | Get-Help -detailed | Out-File <C>:\<FolderName>\VMMHelpTopics.txt Replace "<C>" with the letter of the drive on which you want to store VMMHelpTopics, and replace "<FolderName>" with the name of the folder on that drive in which you want to store VMMHelpTopics. If you see an error message indicating that a Help topic for one or more cmdlets could not be found, the command should still run correctly and should put a copy of all existing cmdlet Help topics into the VMMHelpTopics.txt file. 2. To confirm that the text file contains the Help topics for all Virtual Machine Manager cmdlets, open Windows Explorer and then open VMMHelpTopics.txt in the folder in which you stored the file. |
Useful Windows PowerShell Command-Line Help Topics
To list the standard Windows PowerShell conceptual topics, type:
Get-Command about_*
To view any of these topics, type:
Get-Help about_<TopicName>
143