Automation Using PowerShell


Download Automation Using PowerShell


Preview text

Chapter 8
Automation Using PowerShell
Virtual Machine Manager is one of the first Microsoft software products to fully adopt Windows PowerShell and offer its users a complete management interface tailored for scripting. From the first release of VMM 2007, the Virtual Machine Manager Administrator Console was written on top of Windows PowerShell, utilizing the many cmdlets that VMM offers. This approach made VMM very extensible and partner friendly and allows customers to accomplish anything that VMM offers in the Administrator Console via scripts and automation. Windows PowerShell is also the only public application programming interface (API) that VMM offers, giving both developers and administrators a single point of reference for managing VMM. Writing scripts that interface with VMM, Hyper-V, or Virtual Server can be made very easy using Windows PowerShell’s support for WMI, .NET, and COM.
In this chapter, you will learn to:
◆ Describe the main benefits that PowerShell offers for VMM
◆ Use the VMM PowerShell cmdlets ◆ Create scheduled PowerShell scripts
VMM and Windows PowerShell
System Center Virtual Machine Manager (VMM) 2007, the first release of VMM, was one of the first products to develop its entire graphical user interface (the VMM Administrator Console) on top of Windows PowerShell (previously known as Monad). This approach proved very advantageous for customers that wanted all of the VMM functionality to be available through some form of an API. The VMM team made early bets on Windows PowerShell as its public management interface, and they have not been disappointed with the results. With its consistent grammar, the great integration with .NET, and the abundance of cmdlets, PowerShell is quickly becoming the management interface of choice for enterprise applications.
Unlike other traditional public APIs that focus on developers, VMM’s PowerShell interface is designed for the administrator. With the extensive help contents and the well-documented System Center Virtual Machine Manager Scripting Guide that is available from the Microsoft Download Center, the VMM team positioned its cmdlets to be the premier way of scripting in your virtualization environment. In addition to the VMM cmdlets, your scripts can be enhanced by the built-in support that Windows PowerShell has for a variety of data stores, like the filesystem, the Registry, and WMI.

328 CHAPTER 8 AUTOMATION USING POWERSHELL
Installing the VMM PowerShell Cmdlets
Even though the VMM PowerShell interface does not have its own installer, it is always installed as part of the VMM Administrator Console setup. VMM Setup will install the 32-bit version of the Administrator Console on 32-bit systems and the 64-bit version of the Administrator Console on 64-bit systems. Due to the nature of the VMM cmdlets, some utilize both native and .NET binaries in their implementation. This approach prohibits the VMM PowerShell cmdlets from being architecture independent, which means that only 32-bit PowerShell cmdlets will work on a 32-bit system. The 64-bit PowerShell cmdlets have the same issue and will work on only a 64-bit system. Any process that attempts to load the PowerShell runspace and invoke the VMM cmdlets needs to be aware of this restriction and factor this limitation in the design.
VMM 2008 is certified to work with both Windows PowerShell version 1.0 and version 2.0. Windows PowerShell is already included as part of Windows Server 2008 and Windows Server 2008 R2, and it can be downloaded for free from the Microsoft website at the following location:
http://www.microsoft.com/windowsserver2003/technologies/management/powershell/ download.mspx Windows PowerShell 1.0 officially supports Windows XP Service Pack 2, Windows Server 2003, Windows Vista, and Windows Server 2008. Windows PowerShell 2.0 was released with the Windows 7 and Windows Server 2008 R2 operating systems. PowerShell 2.0 will be eventually pack-ported to other operating systems as well. When you first launch Windows PowerShell in your system and import the VMM PowerShell snap-in, you will be prompted to add Microsoft Corporation to the list of trusted publishers, as per Figure 8.1. Enter A in this case for Always Run.
Figure 8.1 Adding Microsoft Corporation to the list of trusted publishers for Windows PowerShell scripts
It is possible Windows PowerShell will still prevent you from running scripts in your system, so you need to set the proper execution policy for scripts before any Windows PowerShell scripts are allowed to run on your computer. This can be achieved using the Set-ExecutionPolicy cmdlet. Figure 8.2 shows the help contents of this cmdlet. Type in get-help Set-ExecutionPolicy -detailed | more for more information on the policy options. To invoke the Set-ExecutionPolicy cmdlet, you need to run Windows PowerShell as Administrator.

Figure 8.2 Setting the execution policy for Windows PowerShell

VMM AND WINDOWS POWERSHELL 329

Exposing the VMM Cmdlets
To get started with VMM and Windows PowerShell, open a console window that has the VMM PowerShell snap-in loaded. There are a few ways to accomplish this, as shown here:
1. Click Start All Programs Microsoft System Center Virtual Machine Manager 2008 R2 and launch Windows PowerShell - Virtual Machine Manager. This command will automatically launch Windows PowerShell version 1.0 and pass as input the VMM PowerShell Console file located at
%SystemDrive%\Program Files\Microsoft System Center Virtual Machine Manager 2008 R2\bin\cli.psc1
2. Open a regular Windows PowerShell console window and add the VMM snap-in using the following command. Once the VMM snap-in is added, you can use all the VMM cmdlets.
Add-PSSnapin "Microsoft.SystemCenter.VirtualMachineManager"
3. Windows PowerShell can also be launched from the Administrator Console by clicking the PowerShell button in the toolbar of the main view.

330 CHAPTER 8 AUTOMATION USING POWERSHELL

Once the VMM PowerShell snap-in is added, you can get a list of all VMM cmdlets using the get-command cmdlet.
# This cmdlet will get all cmdlets that can be executed by the currently # loaded PowerShell snapins Get-command
# This cmdlet will list only the cmdlets exposed by the VMM Windows # PowerShell snapin get-command -module "Microsoft.SystemCenter.VirtualMachineManager"

Getting Help on VMM Cmdlets
If you have the name of a VMM cmdlet, you can get more information on it, including a list of examples. The following code shows how to get the definition of the Refresh-VM cmdlet:

PS D:\> get-command refresh-vm

CommandType ----------Cmdlet

Name ---Refresh-VM

Definition ---------Refresh-VM [-VM] [-RunA...

The following code shows how to get the detailed view of the parameters that can be passed to the Refresh-VM cmdlet:

PS D:\> get-command refresh-vm | format-list

Name CommandType Definition

: Refresh-VM : Cmdlet : Refresh-VM [-VM] [-RunAsynchronously] [-JobVariable ring>] [-PROTipID ] [-Verbose] [-Debug] [-ErrorA ction ] [-WarningAction ] [-ErrorVariable ] [-WarningVariable ] [-Ou tVariable ] [-OutBuffer ]

Path

:

AssemblyInfo

:

DLL

: D:\Program Files\Microsoft System Center Virtual Machine Man

ager 2008 R2\bin\Microsoft.SystemCenter.VirtualMachineManager.d

ll

HelpFile

: Microsoft.SystemCenter.VirtualMachineManager.dll-Help.xml

ParameterSets : {[-VM] [-RunAsynchronously] [-JobVariable ] [-P

ROTipID ] [-Verbose] [-Debug] [-ErrorAction
ionPreference>] [-WarningAction ] [-ErrorV

ariable ] [-WarningVariable ] [-OutVariable

] [-OutBuffer ]}

ImplementingType : Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.Refresh

VmCmdlet

VMM AND WINDOWS POWERSHELL 331

Verb Noun

: Refresh : VM

The following code shows how to get the help for the Refresh-VM cmdlet:

PS D:\> get-help refresh-vm

NAME Refresh-VM

SYNOPSIS Refreshes the properties of a virtual machine so that the Virtual Machine M anager Administrator Console displays updated information about the virtual machine.

SYNTAX Refresh-VM [-VM] [] [-JobVariable ] [-PROTipID ] [ -RunAsynchronously] []

DETAILED DESCRIPTION Refreshes the properties of a virtual machine so that the Virtual Machine M anager Administrator Console displays updated information about the virtual machine. The updated properties include Name, Location, Status, OperatingS ystem, and other properties.

RELATED LINKS Get-VM Refresh-LibraryShare Refresh-VMHost

REMARKS To see the examples, type: "get-help Refresh-VM -examples". For more information, type: "get-help Refresh-VM -detailed". For technical information, type: "get-help Refresh-VM -full".
The next code shows the different parameters that can be passed to the get-help cmdlet:

# To show detailed information on the refresh-vm cmdlet, use the # -detailed parameter PS D:\> get-help Refresh-VM -detailed

# This command will show examples on using the cmdlet refresh-vm PS D:\> get-help Refresh-VM -examples

# This command will show the full information on using the refresh-vm cmdlet PS D:\> get-help Refresh-VM -full

Some VMM cmdlets offer different parameters sets. In Figure 8.3 and Figure 8.4, you can see the different parameter sets for the Get-VM cmdlet. For example, you can get a

332 CHAPTER 8 AUTOMATION USING POWERSHELL list of virtual machines (VMs) by a matching name, by using the ID of the VM object, or by executing the cmdlet against a specific host. Any parameter that is included in square brackets is optional. If a required parameter is not specified, PowerShell will prompt for it as Figure 8.5 shows.
Figure 8.3 Get-VM’s different parameter sets
Using the VMM Cmdlets
By now you know how to get a list of all VMM cmdlets and their descriptions. To get more information about each cmdlet, including details on each parameter and examples on how to invoke them, you can use the get-help cmdlet with the -full, -examples, or -detailed parameter.

Figure 8.4 Get-VM’s required parameters

VMM AND WINDOWS POWERSHELL 333

Figure 8.5 Windows PowerShell will prompt for required parameters.

334 CHAPTER 8 AUTOMATION USING POWERSHELL
The Virtual Machine Manager Scripting Guide is also a great reference for learning how to use Windows PowerShell with VMM. VMM published a scripting guide with both VMM 2007 and VMM 2008. You can find the scripting guides at http://www.microsoft.com/downloads/ details.aspx?familyid=3DA5BA7E-AD72-4D2C-B573-1B74894D1DDF&displaylang=en and at http://technet.microsoft.com/en-us/library/cc764259.aspx. A scripting guide update for VMM 2008 R2 should be available on the System Center Virtual Machine Manager TechCenter shortly.
Appendix B, ‘‘VMM Windows PowerShell Object Properties and VMM Cmdlet Descriptions,’’ contains a reference list of Virtual Machine Manager cmdlets and a short description of their functionality.
Noun Properties
Windows PowerShell uses a verb-noun format for the names of the cmdlets. The verb identifies the action to be performed, such as get, add, set, remove, or new. The Windows PowerShell team has a published list of common verbs for cmdlet developers to adhere to.
The noun identifies the type of object on which the cmdlet will operate. Example nouns include VM (virtual machine), VMHost (virtualization host), VMHostCluster (Failover Cluster), and VirtualNetwork (virtual network). In this section, we will look at three of the most frequently used nouns in VMM and explain their property values.
VMM cmdlets will in most cases return back to the pipeline the noun of the cmdlet. This allows you to use the pipeline and combine multiple VMM cmdlets for more complicated scripts. For Get-* cmdlets, like Get-VM for example, it is possible for the value that is returned to the pipeline to be a collection instead of a single object. You can check the type of the return value using the code snippet in the next paragraph.
PowerShell Pipeline
The PowerShell pipeline is similar in concept to the ‘‘pipeline’’ seen in Unix shell scripting environments. The pipeline allows you to create a multitude of single-purpose and easy-to-understand cmdlets and then combine them to achieve a bigger task (just like building blocks).
The following code shows how to invoke the Get-VM cmdlet and check the result:
# Execute Get-VM on a VM that does not exist. In this case $vm should be null $vm = Get-VM "VMDoesNotExist" $vm -eq $null
# Execute Get-VM as a targeted get for a single VM. In this case # the result should not be an array $vm = Get-VM "virtualmachine1" $vm -is [Array]
# Execute Get-VM to get all VMs in the system. In this case the # result may be an array $vm = Get-VM $vm -is [Array]

VMM AND WINDOWS POWERSHELL 335
VMMServer Object
VMMServer represents the object that contains the connection to the Virtual Machine Manager. This object also contains some of the global settings of the VMM server installation and environment. Once a connection to the VMM server is established, the connection is cached and future cmdlets that need a connection object will automatically use the existing cached connection.
To see the VMMServer noun and a list of its properties with an explanation for each property, see Appendix B.
VM Object
VM represents the object that contains a virtual machine instance in Virtual Machine Manager. To see the virtual machine noun and its properties, see Appendix B. Each property also con-
tains a definition for its value or values.
VMHost Object
VMHost represents the object that contains a physical computer that is a virtual machine host. A virtual machine host could be a Virtual Server host, a Hyper-V host, or a VMware ESX host. The following code shows you how to get a list of all the properties of a host and inspect their values:
PS D:\> $vmhost = Get-VMHost "hostname" PS D:\> $vmhost
Windows PowerShell will output all the properties and values for the supplied host.
To see the VMHost noun and its properties, see Appendix B. Each property also contains a definition for its value or values.
Leveraging the Public PowerShell API
Virtual Machine Manager uses the Windows PowerShell cmdlets for VMM as the single point of entry for VMM. Developers can integrate with VMM programmatically by leveraging the publicly available VMM PowerShell cmdlets. Calling cmdlets programmatically is not much different than invoking them in a Windows PowerShell command window. In this section, we will look at programmatically invoking the cmdlets and give you example code to achieve this type of integration with VMM.
Programmatically Calling the VMM Cmdlets
The set of Windows PowerShell cmdlets for VMM is the only supported API for integrating with VMM. To programmatically call the cmdlets and manage VMM, you would need to create a PowerShell runspace and invoke the cmdlets in the same way you would if you were using the Windows PowerShell command window.
To start, you need to know the path to the VMM assemblies that are needed to resolve the VMM objects and cmdlets. You can find the installation path for the Virtual Machine Manager Administrator Console under the Registry key HKLM\Software\Microsoft\Microsoft System Center Virtual Machine Manager Administrator Console\Setup. The InstallPath value of

336 CHAPTER 8 AUTOMATION USING POWERSHELL

this Registry key contains the root of the installation path for VMM. The four assemblies that are needed for the programmatic usage of VMM cmdlets are located in the bin folder of the installation directory. These binaries are listed here:
◆ Microsoft.SystemCenter.VirtualMachineManager.dll
◆ Remoting.dll
◆ Utils.dll
◆ Errors.dll
Because none of these VMM assemblies are listed in the Global Assembly Cache (GAC), if you want your application to be able to resolve them without copying the binaries, you need to use an assembly resolve handler. The following code shows you how to add such a handler and how to properly load the correct assembly. The InstallPath value from the Registry is needed for this purpose:

// Add the code for the assembly resolver before any of the VMM binaries are invoked. Thread.GetDomain().AssemblyResolve += new
ResolveEventHandler(VMMResolveEventHandler);

// In this example, we automatically resolve everything to the VirtualMachineManager DLL. A smart resolver would look at the args.Name and match the assembly to be resolved with its proper full path. static Assembly VMMResolveEventHandler(object sender, ResolveEventArgs {
return Assembly.LoadFrom("D:\Program Files\Microsoft System Center Virtual Machine Manager 2008 R2\bin\ Microsoft.SystemCenter.VirtualMachineManager.dll"); }

args)

In addition to the required binaries, the WCF port number of the VMM server is needed to establish a successful connection. You can find the TCP port number for WCF under the VMM server Registry key HKLM\Software\Microsoft\Microsoft System Center Virtual Machine Manager Server\Settings. The IndigoTcpPort value contains the port number that all VMM clients need to use to connect.
Now we have all the data we need to connect to VMM and execute some PowerShell cmdlets. It is recommended to use a utility to create a wrapper on top of the VMM PowerShell snap-in. Such a wrapper would produce a familiar .NET interface for developers and provide type safety for all PowerShell cmdlets. There are a few publicly available tools to create such wrappers. In the following example, I am using the native PowerShell implementation, directly invoking cmdlets using their string names. You can see that any mistakes in this code will not be caught by the compiler.
Listing 8.1 is a complete program that creates a PowerShell runspace, adds the VMM PowerShell snap-in to it, creates a connection to the VMM server on default port 8100, and gets a list of all VMs that the current user is authorized to see. The list of VMs returned is written on the console window as in Figure 8.6.

Preparing to load PDF file. please wait...

0 of 0
100%
Automation Using PowerShell