Automating VMware Horizon 7 with VMware PowerCLI 6.5

Automating VMware Horizon 7 with VMware PowerCLI 6.5

This post was originally published on this site ---

With VMware PowerCLI 6.5 Release 1, the automation of VMware Horizon 7 matures and we get integrated PowerShell support for the View component of Horizon 7 built into VMware PowerCLI. We have a proper Horizon 7 module that is distributed and ships with the core VMware PowerCLI installation.

For information about all the new features of VMware PowerCLI 6.5 R1, see the New Release: PowerCLI 6.5 R1 blog post.

So, what do we get with the release of the new VMware PowerCLI Horizon 7 module? We actually get three things: the Horizon 7 module itself, access to the View API with online documentation, and a set of advanced functions released on GitHub.

PowerCLI Horizon Resources

VMware PowerCLI – Horizon 7 Module

Even though the Horizon 7 module contains only two cmdlets, they are extremely useful. These cmdlets allow you to connect and disconnect from the View API service. Importantly, this functionality provides a convenient way to access the full View API and the capabilities normally only available through the Horizon Administrator console.

Unlike previous VMware PowerCLI for Horizon 7 implementations, you can now connect and run VMware PowerCLI scripts for Horizon 7 from remote workstations or servers, such as an administrator’s desktop, using different credentials. You can also easily build federated scripts across VMware assets. For example, you can write a script to get a list of datastores from a vCenter Server inventory and use that information to select the best datastores on which to create a pool.

View API

To accompany the new VMware PowerCLI module, VMware is happy to announce the release of public View API Reference Documentation for Horizon 7 and access to the full public View API. The View API is a web service and is available from any Horizon Connection Server within a Horizon Pod. The View API is used by the Horizon Administrator console for configuration, administration, and monitoring, so we are now exposing programmatic access to all the functionality available in the console.

To make exploring the data objects and methods of interacting with them easier, VMware has created a new Developer Center online API Explorer, a unified interface for all API documentation across the VMware stack.

Advanced Functions

To get you started quickly, the Horizon 7 team has put together a set of functions that cover common operations. These functions allow you to easily interact with pools, farms, and desktops without having to write scripts from scratch. Be sure to visit the VMware PowerCLI Community Repository site on GitHub periodically to get new functions and consider contributing your own.

Installation

Install VMware PowerCLI

  1. Download the VMware PowerCLI 6.5 R1 installer and run the installation wizard.
  2. As part of the installation, you are prompted to change the ExecutionPolicy of PowerShell.
  3. Launch PowerShell (run as Administrator), and run the following command.
Set-ExecutionPolicy RemoteSigned

Install Advanced Functions

  1. Go to the GitHub repository page at  https://github.com/vmware/PowerCLI-Example-Scripts.
  2. Click the green Clone or download button and then click Download ZIP.Advanced Functions Download
  3. Extract the zip file and copy the advanced functions Hv.Helper folder to a modules directory.
  4. Check your PowerShell $env:PSModulePath variable to see which directories are in use:
    • User specific: %UserProfile%DocumentsWindowsPowerShellModules
    • System wide: C:Program FilesWindowsPowerShellModules
  5. Unblock the advanced functions to allow them to be executed.
    • In a PowerShell prompt (as Administrator), run the following command, tailoring the path to where you copied the VMware.Hv.Helper folder:
dir ‘C:Program FilesWindowsPowerShellModulesVMware.HvHelper’ | Unblock-File

Locate documentation

Getting Started

Launching PowerShell by using the VMware PowerCLI shortcut created during installation loads all the VMware modules, including the one for Horizon 7. If you use a normal PowerShell shortcut you have to load the modules as part of your script.

You can import all of the VMware modules or just the Horizon 7 module, though you need the Core module too if you plan on interacting with VMware vSphere. To load all the modules, use the following command:

Get-Module -ListAvailable VMware* | Import-Module

To load only the Horizon 7 module or the Horizon 7 module and the Core module, use one or both of the following commands:

Import-Module VMware.VimAutomation.HorizonView
Import-Module VMware.VimAutomation.Core

You can now connect to the Horizon Connection Server and the View API using your credentials:

Connect-HVServer -server horizon1.mydomain.com

In this example, horizon1.mydomain.com is one of the Horizon Connection Servers.

You are prompted for credentials, but you could alternatively include your credentials in the command.

Connect-HVServer -server horizon1.mydomain.com -user demoadmin -password mypassword -domain mydomain

Connect-HVServer

A global variable called DefaultHVServers is created, which stores information about connections to the Horizon Connection Servers. You can access this variable with $Global:DefaultHVServers.

DefaultHVServers Variable

All the interesting stuff is really under ExtensionData. To make working with this property a bit easier we will assign it to a variable $Services1 and take a look.

$Services1=$Global:DefaultHVServers.ExtensionData
$Services1

ExtensionData

Looking at the View API reference documentation you will start to recognize some of these entries. The ExtensionData property (and now the $Services1 variable) holds access to the entire View API.

Examples

Let’s run a couple of commands and start to explore how we can use the VMware PowerCLI. Remember we have access to the full View API!

First, let’s use a simple View API command and get a list of all the Horizon Connection Servers in the pod. The commands in the following example use the View API service ConnectionServer and method ConnectionServer_List and assign the results to variable $hvServers1. For more information about this service, see the View API reference documentation.

$hvServers1 = $Services1.ConnectionServer.ConnectionServer_List()
$hvServers1.General

Horizon Connection Servers List

Next, let’s use one of the advanced functions to get a list of desktops, depending on the state of the Horizon Agent. This listing is useful for understanding the state of the desktops, including whether they are in use, available for new user connections, or in an error state.

The following command returns a list of the desktops which have users logged in but the user is currently disconnected from the desktop:

$DisconnectedVMs = Get-HVMachineSummary -State DISCONNECTED
$DisconnectedVMs | Out-GridView

Disconnected Virtual Machines

For a complete list of possible states, check out the View API documentation on baseState.

It would be useful to get a list of problem VMs with agent states that include the following:

PROVISIONING_ERROR, ERROR, AGENT_UNREACHABLE, AGENT_ERR_STARTUP_IN_PROGRESS, AGENT_ERR_DISABLED, AGENT_ERR_INVALID_IP, AGENT_ERR_NEED_REBOOT, AGENT_ERR_PROTOCOL_FAILURE, AGENT_ERR_DOMAIN_FAILURE, AGENT_CONFIG_ERROR, UNKNOWN

You can modify the command used above to return a list of desktops with one of these states by replacing the state to check for. For example:

$ProblemVMs = Get-HVMachineSummary -State AGENT_UNREACHABLE

You can take this further and use a script to list desktops with the Horizon Agent in a number of different problem states. You could then carry out tasks to remediate the problems. The following sample script gets all the problem desktops by querying the View API using this advanced function. The script then uses a vSphere command to reboot the problem VMs.

In the script, replace the values for the variables to indicate your Horizon Connection Server, user name, and so on.

Also, consider adding a -WhatIf parameter to the Restart-VMGuest command. A -WhatIf parameter shows you the outcome without actually executing the command.

####################################################################
# Get List of Desktops that have Horizon Agent in problem states.
# Reboot the OS of each these.
####################################################################

#region variables
###################################################################
#                    Variables                                   #
###################################################################
$cs = 'horizon1.mydomain.com' #Horizon Connection Server
$csUser= 'demoadmin' #User account to connect to Connection Server
$csPassword = 'mypassword' #Password for user to connect to Connection Server
$csDomain = 'mydomain' #Domain for user to connect to Connection Server

$vc = 'vcenter1.mydomain.com' #vCenter Server
$vcUser = 'administrator@vsphere.local' #User account to connect to vCenter Server
$vcPassword = 'mypassword' #Password for user to connect to vCenter Server

$baseStates = @('PROVISIONING_ERROR',
                'ERROR',
                'AGENT_UNREACHABLE',
                'AGENT_ERR_STARTUP_IN_PROGRESS',
                'AGENT_ERR_DISABLED',
                'AGENT_ERR_INVALID_IP',
                'AGENT_ERR_NEED_REBOOT',
                'AGENT_ERR_PROTOCOL_FAILURE',
                'AGENT_ERR_DOMAIN_FAILURE',
                'AGENT_CONFIG_ERROR',
                'UNKNOWN')
#endregion variables

#region initialize
###################################################################
#                    Initialize                                  #
###################################################################
# --- Import the PowerCLI Modules required ---
Import-Module VMware.VimAutomation.HorizonView
Import-Module VMware.VimAutomation.Core

# --- Connect to Horizon Connection Server API Service ---
$hvServer1 = Connect-HVServer -Server $cs -User $csUser -Password $csPassword -Domain $csDomain

# --- Get Services for interacting with the View API Service ---
$Services1= $hvServer1.ExtensionData

# --- Connect to the vCenter Server ---
Connect-VIServer -Server $vc -User $vcUser -Password $vcPassword

#endregion initialize

#region main
###################################################################
#                    Main                                        #
###################################################################
Write-Output ""
if ($Services1) {
     foreach ($baseState in $baseStates) {
           # --- Get a list of VMs in this state ---
           $ProblemVMs = Get-HVMachineSummary -State $baseState

           foreach ($ProblemVM in $ProblemVMs) {
                $VM = Get-VM -Name $ProblemVM.Base.Name
                # --- Reboot each of the Problem VMs ---
                Restart-VMGuest -VM $VM
                # Add -WhatIf to see what would happen without actually carrying out the action.
           }
     }
     Write-Output "", "Disconnect from Connection Server."
     Disconnect-HVServer -Server $cs
} else {
     Write-Output "", "Failed to login in to Connection Server."
     pause
     }
# --- Disconnect from the vCenter Server ---
Write-Output "", "Disconnect from vCenter Server."
Disconnect-VIServer -Server $vc
#endregion main

Summary

These have been fairly simple examples, but these and the installation instructions should be enough to get you going. These examples only scratched the surface of what is possible. Now that you are armed with the new PowerCLI module for Horizon, access to the View API, the documentation, and the advanced functions, you can start to explore new ways of automating your Horizon 7 environment.

Let us know how you get on, what use cases and problems you solve, and be sure to feed your scripts back into the community for others to benefit from.

The post Automating VMware Horizon 7 with VMware PowerCLI 6.5 appeared first on VMware End-User Computing Blog.

Leave a Reply

Your email address will not be published. Required fields are marked *