VMware Horizon Technical Guides

Automating VMware Horizon 8 with VMware PowerCLI

VMware PowerCLI integrates PowerShell support for VMware Horizon to allow for programmatic control and automation through the View API. 

In addition to the View API, Horizon also has a full RESTful API, the VMware Horizon Server API, which can also be used to interact with and to automate a Horizon environment. See Using the VMware Horizon Server REST API for more details. 

With the VMware PowerCLI Horizon functionality, you’ll receive three things: the Horizon PowerCLI module itself, access to the View API with online documentation, and a set of advanced functions released on GitHub. 

PowerCLI graph

VMware Horizon PowerCLI module 

Even though the Horizon PowerCLI module contains only two cmdlets, they are extremely useful. These cmdlets allow you to connect and disconnect from the View API service. This functionality provides a convenient way to access the full View API and all the capabilities available through the Horizon Console. 

This module allows you to connect and run VMware PowerCLI scripts for Horizon from remote workstations or servers, such as an administrator’s desktop, using different credentials. You can also easily build federated scripts across VMware products. 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 VMware PowerCLI module, there is also public View API Reference Documentation for Horizon 7 and 8 and access to the full public View API. The View API is a web service and is available from any Connection Server within a Horizon pod. 

Advanced functions 

To get you started quickly, the Horizon 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 

To get started you need to: 

  • Install VMware PowerCLI 
  • Download and install the advanced functions 
  • Know where to find the reference documentation  

1. Install VMware PowerCLI. For full instructions, see the PowerCLI Installation Guide.

a. For Windows, open a Windows PowerShell (Admin) console and run the following command.

Install-Module VMware.PowerCLI

b. Allow Execution of Local Scripts

Set-ExecutionPolicy RemoteSigned

c. See the VMware PowerCLI User’s Guide for more information.

2. Install the Horizon advanced functions:

a. Browse to the GitHub repository page at  https://github.com/vmware/PowerCLI-Example-Scripts.

b. Click the green Clone or download button and then click Download ZIP.

PowerCLI example scripts

c. Extract the zip file and copy the advanced functions Hv.Helper folder (inside the modules folder) to one of the modules directories on your computer.

• Check your PowerShell $env:PSModulePath variable to see which directories are in use:

• User specific: %UserProfile%\Documents\WindowsPowerShell\Modules

• System wide: C:\Program Files\WindowsPowerShell\Modules

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

Files\WindowsPowerShell\Modules\VMware.HvHelper\’ |

Unblock-File

3. Locate documentation:

• Bookmark the View API Reference Documentation.

• Bookmark the VMware PowerCLI Cmdlets Reference

Getting started 

Launch PowerShell and load any of the VMware modules required. You can import all the VMware modules or just the Horizon module. You will 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 module and the Core module, use 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 s1-hcs1.mydomain.com 

In this example, s1-hcs1.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

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

$services=$Global:DefaultHVServers.ExtensionData 

$services 

$Services

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

Examples of how to use VMware PowerCLI  

Let’s run a couple of commands and start to explore how we can use the VMware PowerCLI. 

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.  

$hvservers = $services.ConnectionServer.ConnectionServer_List() 

$hvservers.General 

hvservers

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 

$DisconnectedVMs

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 Connection Server, username, and so on. If you prefer not to include the user credentials in the script, you can remove these from the Connect-HVServer and Connect-VIServer commands, and instead be prompted for credentials. 

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 of these. 

#################################################################### 

#region variables 

################################################################### 

# Variables 

################################################################### 

$cs = 's1-hcs1.mydomain.com' #Horizon Connection Server 

$csUser = 'administrator' #Connection Server user 

$csPassword = 'mypassword' #Connection Server user password 

$csDomain = 'mydomain' #Connection Server domain 

$vc = 'vcenter1.mydomain.com' #vCenter Server 

$vcUser = '[email protected]' #vCenter Server user 

$vcPassword = 'mypassword' #vCenter Server password 

$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 

Set-PowerCLIConfiguration -InvalidCertificateAction Prompt 

# --- Connect to Horizon Connection Server API Service --- 

$hvServer = Connect-HVServer -Server $cs -User $csUser -Password $csPassword -Domain $csDomain 

# --- Get Services for interacting with the View API Service --- 

$services= $hvServer.ExtensionData 

# --- Connect to the vCenter Server --- 

Connect-VIServer -Server $vc -User $vcUser -Password $vcPassword 

#endregion initialize 

#region main 

################################################################### 

# Main 

################################################################### 

Write-Output "" 

if ($services) { 

         foreach ($baseState in $baseStates) { 

                # --- Get a list of VMs in this state --- 

                Write-Host ("Get VMs with baseState: " + $baseState)     -ForegroundColor Yellow 

                $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 into 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 of how to use PowerCLI for Horizon 8, 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 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 8 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.