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.

      Warning

      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'
    

    Note

    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
    

    Note

    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:

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

      Note

      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.

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

    3. 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
      
    4. 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

    Note

    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.

Warning

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 https://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:

Note

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" (https://go.microsoft.com/fwlink/?LinkId=98347).

For More Information

For Windows PowerShell topics that are available on the Microsoft Web site:

For Virtual Machine Manager topics that are available on the Microsoft Web site:

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